To get list of contact s is one the common task, when one is going for iOS app development. For that we have multiple choice like Address Book, Contact ...
Here i am going to show how to can we get list of saved contact in iOS programming using Objective C. I am using "Contacts Framework" to get list of contact. Since it is new class in iOS9. so there are very few resources on web. But it is very easy to get contact list using Contacts framework and CNContactStore Class.
How to go
There are few easy step and some line of and we can get an array of contact.
- add contacts frame work
- click on app main file name -> General -> and in linked framework and library click on + then add Contacts.framework
- Then import Contacts/Contacts.h in view controller
- To get list of all contact here is the code
here firstly we check for existence of class. If it is, we are creating a an object of CNContactStore to store our data.
if([CNContactStore class])
CNContactStore* contactStoredData = [[CNContactStore alloc] init];
next line is for "key'. Here we specify the key information in an array. The key array contains all key that has to fetch. Here i am fetching family name, given name, middle name and phone number. while you can add any number of key as per your need.
NSArray* keyToFetch = @[CNContactFamilyNameKey,
CNContactGivenNameKey,
CNContactMiddleNameKey,
CNContactPhoneNumbersKey];
Once the key array is set what we have to do to create a fetch request with specified key. And this is a easy task using CNContactFetchRequest as
CNContactFetchRequest* fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keyToFetch];
After setting all keys and creating request we can request for contact which is
[contactStoredData enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop){
[contacts addObject:contact]; // adding a contact to contacts array
}];
enumerateContactsWithFetchRequest will fetch contact one by one and we can store it in our array. which am doing as
[contacts addObject:contact];
Once all contacts are fetched, then we have an array of CNContact. ie each element of array contact an object of contact. Now from this array we can get name, phone no, address etc.
Now to get information from CNContact, we can easily fetch it as
(Here "contact" is object of CNContact)
NSString* firstName = contact.givenName;
NSString* middleName = contact.middleName;
NSString* lastName = contact.familyName;
NSArray* phoneNO = [[contact.phoneNumbers valueForKey:@"value"] valueForKey:@"digits"];
Here we are getting list of phone no associate with a contact object. Now it is easy to show list of phone no along with his/her name;
here is complete project that fetch list of contact from phone and show name and phone no in table view. :)
No comments:
Post a Comment