// Import two framework
#import <AddressBookUI/AddressBookUI.h>
#import <AddressBook/AddressBook.h>
// create a property
@property (nonatomic, assign) ABAddressBookRef addressBookRef;
// in view didLoad
ABAddressBookRequestAccessWithCompletion(self.addressBookRef, ^(bool granted, CFErrorRef error) {
if (granted) {
dispatch_async(dispatch_get_main_queue(), ^{
[self getContactsFromAddressBook];
});
} else {
// TODO: Show alert
}
});
-(void)getContactsFromAddressBook
{
CFErrorRef error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
if (addressBook) {
NSArray *allContacts = (__bridge_transfer NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);
NSUInteger i = 0;
for (i = 0; i<[allContacts count]; i++) {
// myClass *shrObj = [[myClass alloc] init];
ABRecordRef contactPerson = (__bridge ABRecordRef)allContacts[i];
// Get first and last names
NSString *firstName = (__bridge_transfer NSString*)ABRecordCopyValue(contactPerson, kABPersonFirstNameProperty);
NSString *lastName= (__bridge_transfer NSString*)ABRecordCopyValue(contactPerson, kABPersonLastNameProperty);
if (!lastName) {
lastName=@"";
}
NSString *fullName = [NSString stringWithFormat:@"%@ %@",firstName,lastName];
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
[dict setValue:fullName forKey:@"name"];
// Get mobile number
ABMultiValueRef phonesRef = ABRecordCopyValue(contactPerson, kABPersonPhoneProperty);
if ([self getMobilePhoneProperty:phonesRef]!=nil) {
[dict setValue:[self getMobilePhoneProperty:phonesRef] forKey:@"mobile"];
[arrContact addObject:dict];
}
if(phonesRef) {
CFRelease(phonesRef);
}
}
[tblContact reloadData];
}
else
{
NSLog(@"Error");
}
}
- (NSString *)getMobilePhoneProperty:(ABMultiValueRef)phonesRef {
for (int i=0; i < ABMultiValueGetCount(phonesRef); i++) {
CFStringRef currentPhoneLabel = ABMultiValueCopyLabelAtIndex(phonesRef, 0);
CFStringRef currentPhoneValue = ABMultiValueCopyValueAtIndex(phonesRef, 0);
if(currentPhoneLabel) {
if (CFStringCompare(currentPhoneLabel, kABPersonPhoneMobileLabel, 0) == kCFCompareEqualTo) {
return (__bridge NSString *)currentPhoneValue;
}
if (CFStringCompare(currentPhoneLabel, kABHomeLabel, 0) == kCFCompareEqualTo) {
return (__bridge NSString *)currentPhoneValue;
}
}
if(currentPhoneLabel) {
CFRelease(currentPhoneLabel);
}
if(currentPhoneValue) {
CFRelease(currentPhoneValue);
}
}
return nil;
}