ABAddressBook Helper
Hey everyone, while working on my latest project, i discovered the need to search the address book for a phone number. Through my travels, I DID discover that it seems this functionality isn’t exposed by default with the native iOS libraries, or if it is, its with NSArrays, and NSObjects which can be slower than native MT components. So with a bit of help from Clancy, i came up with this helper class for the MonoTouch ABAddressBook. Enjoy.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | public class ContactHelper { public ContactHelper() { } public static ABPerson PickContact(UIViewController view) { ABPeoplePickerNavigationController picker = new ABPeoplePickerNavigationController(); ABPerson ret = null; picker.SelectPerson += delegate(object sender, ABPeoplePickerSelectPersonEventArgs e) { picker.DismissModalViewControllerAnimated(true); ret = e.Person; }; picker.Cancelled += delegate { picker.DismissModalViewControllerAnimated(true); }; view.PresentModalViewController(picker, true); return ret; } public static ABPerson SearchByPhoneNumber(string phoneNumber) { List singlePeople = new List(); phoneNumber = Regex.Replace(phoneNumber, "[^0-9]", ""); ABAddressBook ab = new ABAddressBook(); var people = ab.Where(x => x is ABPerson).Cast().Where( x => x.GetPhones().Where(p => Regex.Replace(p.Value, "[^0-9]", "").Contains(phoneNumber) || phoneNumber.Contains(Regex.Replace(p.Value, "[^0-9]", ""))).Count() > 0).ToArray(); foreach (var person in people) { if (singlePeople.Intersect(person.GetRelatedNames().Cast()).Count() <= 0) singlePeople.Add(person); } return singlePeople.ToArray().First(); } } |