IOS obtains the address book
1. Add the AddressBook Library
-(IBAction) add :( id) sender {
ABAddressBookRequestAccessWithCompletion (ABAddressBookRef addressBookRef, ^ (bool granted, CFErrorRef error ){
If (granted ){
Dispatch_async (dispatch_get_main_queue (), ^ {
NSArray * array = [selfgetContactsFromAddressBook];
});
} Else {
// TODO: Show alert
}
});
}
-(NSMutableArray *) getContactsFromAddressBook
{
CFErrorRef error = NULL;
NSMutableArray * contacts = [[NSMutableArrayalloc] init];
ABAddressBookRef addressBook = abaddressbookcreatewitexceptions (NULL, & error );
If (addressBook ){
NSArray * allContacts = (_ bridge_transferNSArray *) ABAddressBookCopyArrayOfAllPeople (addressBook );
NSMutableArray * mutableContacts = [NSMutableArrayarrayWithCapacity: allContacts. count];
NSUInteger I = 0;
For (I = 0; I <[allContactscount]; I ++)
{
// THContact a model object with two attributes: name and phoneNum
THContact * contact = [[THContactalloc] init];
ABRecordRef contactPerson = (_ bridgeABRecordRef) allContacts [I];
Contact. recordId = ABRecordGetRecordID (contactPerson );
// Get first and last names
NSString * firstName = (_ bridge_transferNSString *) ABRecordCopyValue (contactPerson, kABPersonFirstNameProperty );
NSString * lastName = (_ bridge_transferNSString *) ABRecordCopyValue (contactPerson, kABPersonLastNameProperty );
NSString * midName = (_ bridge_transferNSString *) ABRecordCopyValue (contactPerson, kABPersonMiddleNameProperty );
// Set Contact properties
Contact. firstName = firstName;
Contact. lastName = lastName;
Contact. middleName = midName;
// Get mobile number
ABMultiValueRef phonesRef = ABRecordCopyValue (contactPerson, kABPersonPhoneProperty );
Contact. phone = [selfgetMobilePhoneProperty: phonesRef];
If (phonesRef ){
CFRelease (phonesRef );
}
If (contact. phone. count> 0 ){
[MutableContactsaddObject: contact];
}
}
If (addressBook ){
CFRelease (addressBook );
}
Contacts = [NSMutableArrayarrayWithArray: mutableContacts];
Return contacts;
}
Else
{
NSLog (@ "Error ");
}
Return nil;
}
-(NSMutableArray *) getMobilePhoneProperty :( ABMultiValueRef) phonesRef
{
NSMutableArray * array = [NSMutableArrayarray];
For (int k = 0; k
{
// Obtain the telephone Label
// NSString * personPhoneLabel = (_ bridge NSString *) ABAddressBookCopyLocalizedLabel (ABMultiValueCopyLabelAtIndex (phonesRef, k ));
// Obtain the phone number under the Label
NSString * personPhone = (_ bridgeNSString *) ABMultiValueCopyValueAtIndex (phonesRef, k );
If (personPhone ){
[ArrayaddObject: personPhone];
}
}
Return array;
}