This code works fine with iOS5/iOS6 but not working with iOS7.
CFErrorRef *error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
//ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBook);
for(int i = 0; i < numberOfPeople; i++) {
ABRecordRef person = CFArrayGetValueAtIndex( allPeople, i );
NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
// NSLog(#"Name:%# %#", firstName, lastName);
ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
NSString *phoneNumber;
for (CFIndex i = 0; i < ABMultiValueGetCount(phoneNumbers); i++) {
phoneNumber = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(phoneNumbers, i);
// NSLog(#"phone:%#", phoneNumber);
}
Today updated my example and removed memory leaks :)
+ (NSArray *)getAllContacts {
CFErrorRef *error = nil;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
ABRecordRef source = ABAddressBookCopyDefaultSource(addressBook);
CFArrayRef allPeople = (ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, source, kABPersonSortByFirstName));
//CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
CFIndex nPeople = CFArrayGetCount(allPeople); // bugfix who synced contacts with facebook
NSMutableArray* items = [NSMutableArray arrayWithCapacity:nPeople];
if (!allPeople || !nPeople) {
NSLog(#"people nil");
}
for (int i = 0; i < nPeople; i++) {
#autoreleasepool {
//data model
ContactsData *contacts = [ContactsData new];
ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
//get First Name
CFStringRef firstName = (CFStringRef)ABRecordCopyValue(person,kABPersonFirstNameProperty);
contacts.firstNames = [(__bridge NSString*)firstName copy];
if (firstName != NULL) {
CFRelease(firstName);
}
//get Last Name
CFStringRef lastName = (CFStringRef)ABRecordCopyValue(person,kABPersonLastNameProperty);
contacts.lastNames = [(__bridge NSString*)lastName copy];
if (lastName != NULL) {
CFRelease(lastName);
}
if (!contacts.firstNames) {
contacts.firstNames = #"";
}
if (!contacts.lastNames) {
contacts.lastNames = #"";
}
contacts.contactId = ABRecordGetRecordID(person);
//append first name and last name
contacts.fullname = [NSString stringWithFormat:#"%# %#", contacts.firstNames, contacts.lastNames];
// get contacts picture, if pic doesn't exists, show standart one
CFDataRef imgData = ABPersonCopyImageData(person);
NSData *imageData = (__bridge NSData *)imgData;
contacts.image = [UIImage imageWithData:imageData];
if (imgData != NULL) {
CFRelease(imgData);
}
if (!contacts.image) {
contacts.image = [UIImage imageNamed:#"avatar.png"];
}
//get Phone Numbers
NSMutableArray *phoneNumbers = [[NSMutableArray alloc] init];
ABMultiValueRef multiPhones = ABRecordCopyValue(person, kABPersonPhoneProperty);
for(CFIndex i=0; i<ABMultiValueGetCount(multiPhones); i++) {
#autoreleasepool {
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, i);
NSString *phoneNumber = CFBridgingRelease(phoneNumberRef);
if (phoneNumber != nil)[phoneNumbers addObject:phoneNumber];
//NSLog(#"All numbers %#", phoneNumbers);
}
}
if (multiPhones != NULL) {
CFRelease(multiPhones);
}
[contacts setNumbers:phoneNumbers];
//get Contact email
NSMutableArray *contactEmails = [NSMutableArray new];
ABMultiValueRef multiEmails = ABRecordCopyValue(person, kABPersonEmailProperty);
for (CFIndex i=0; i<ABMultiValueGetCount(multiEmails); i++) {
#autoreleasepool {
CFStringRef contactEmailRef = ABMultiValueCopyValueAtIndex(multiEmails, i);
NSString *contactEmail = CFBridgingRelease(contactEmailRef);
if (contactEmail != nil)[contactEmails addObject:contactEmail];
// NSLog(#"All emails are:%#", contactEmails);
}
}
if (multiEmails != NULL) {
CFRelease(multiEmails);
}
[contacts setEmails:contactEmails];
[items addObject:contacts];
#ifdef DEBUG
//NSLog(#"Person is: %#", contacts.firstNames);
//NSLog(#"Phones are: %#", contacts.numbers);
//NSLog(#"Email is:%#", contacts.emails);
#endif
}
} //autoreleasepool
CFRelease(allPeople);
CFRelease(addressBook);
CFRelease(source);
return items;
}
Actually recently wrote pod in Swift 3 using CNContacts, to whom it may need
Swift ContactBook Picker
Didn't write it myself. But it works with me:
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
ABAddressBookRef addressBook = ABAddressBookCreate( );
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
CFErrorRef *error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBook);
for(int i = 0; i < numberOfPeople; i++) {
ABRecordRef person = CFArrayGetValueAtIndex( allPeople, i );
// NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
// NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
// NSLog(#"Name:%# %#", firstName, lastName);
ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
[[UIDevice currentDevice] name];
//NSLog(#"\n%#\n", [[UIDevice currentDevice] name]);
for (CFIndex i = 0; i < ABMultiValueGetCount(phoneNumbers); i++) {
NSString *phoneNumber = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(phoneNumbers, i);
addressBookNum = [addressBookNum stringByAppendingFormat: #":%#",phoneNumber];
}
}
NSLog(#"AllNumber:%#",addressBookNum);
}
else {
// Send an alert telling user to change privacy setting in settings app
}
and in my .h
#property NSString * addressBookNum;
Related
I have developed an app which is fetching contacts from iphone its working fine in iphone 4 but it is failed to do the same in iphone 5 .
view did load--------
ABAddressBookRef addressBook = ABAddressBookCreate();
CFErrorRef myError = NULL;
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, &myError);
switch (ABAddressBookGetAuthorizationStatus()) {
case kABAuthorizationStatusNotDetermined: {
NSLog(#"kABAuthorizationStatusNotDetermined");
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
// First time access.
AddressBookUpdated(addressBookRef, nil, (__bridge void *)(self));
CFRelease(addressBookRef); void insert();
}); }
break;
case kABAuthorizationStatusRestricted:{
NSLog(#"kABAuthorizationStatusRestricted");
}
break;
case kABAuthorizationStatusDenied:
NSLog(#"kABAuthorizationStatusDenied");
break;
case kABAuthorizationStatusAuthorized:{
NSLog(#"kABAuthorizationStatusAuthorized");
AddressBookUpdated(addressBookRef, nil, (__bridge void *)(self));
CFRelease(addressBookRef);
break;
}}
function for fetching contact in this function i am fetching contacts & taking them in an array
void AddressBookUpdated(ABAddressBookRef addressBook, CFDictionaryRef info, void *context) {
#try{
NSString *userDefKey;
NSString *docsDir;
NSArray *dirPaths;
const char *dbpath;
NSString *databasePath;
sqlite3 *contactDB;
sqlite3 *db;
NSString *dbPath1;
NSString *dbPath;
NSMutableArray *data,*number,*email;
data=[[NSMutableArray alloc]init];
number=[[NSMutableArray alloc]init];
email=[[NSMutableArray alloc]init];
ABAddressBookRevert(addressBook);
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
ABAddressBookRef addressBook1 = ABAddressBookCreate();
NSArray *people1 = (__bridge NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);
for ( int i = 0; i < nPeople; i++ )
{
ABRecordRef person = CFArrayGetValueAtIndex( allPeople, i );
NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
NSString *emailid;
ABMultiValueRef emailProperty = ABRecordCopyValue(person, kABPersonEmailProperty);
// ABMultiValueRef multi = ABRecordCopyValue((__bridge ABRecordRef)(person), kABPersonPhoneProperty);
//NSString *eid=(__bridge NSString *)(ABRecordCopyValue(person, kABPersonEmailProperty));
NSArray *emailArray = (__bridge NSArray *)ABMultiValueCopyArrayOfAllValues(emailProperty);
// NSInteger *i=(__bridge NSInteger*)ABRecordCopyValue(person, kABPersonPhoneMobileLabel);
if(emailArray.count==0)
[email addObject:#" "];
else{
emailid=emailArray[0];
if(emailid.length!=0)
[email addObject:emailid];
}
//NSLog(#"email array %#",eid);
if(lastName.length<1)
{
[data addObject:firstName];
}
else
{
NSString *combined = [NSString stringWithFormat: #"%# %#",
firstName, lastName];
[data addObject:combined];
}
}
//NSLog(#"phone count is %d",data.count);
//number = [NSMutableArray arrayWithCapacity:data.count];
//NSLog(#"phone count is %d",number.count);
for(id person in people1){
//fetch multiple phone nos.
ABMultiValueRef multi = ABRecordCopyValue((__bridge ABRecordRef)(person), kABPersonPhoneProperty);
for (CFIndex j=0; j < ABMultiValueGetCount(multi); j++) {
NSString* phone = (__bridge NSString*)ABMultiValueCopyValueAtIndex(multi, j);
//NSLog(#"phone no is %#",phone);
[number addObject:phone];
}
}
NSLog(#"data is %#",data);
NSLog(#"phone number %#",number);
NSLog(#"email id is %#",email);
}
I am not able to retrieve mobile number from below code, i am trying lots of thing but unable to solve it. please help me
//this below code is for saving mobile number and phone number
ABRecordRef newPerson = ABPersonCreate();
ABMultiValueAddValueAndLabel(phone, (__bridge CFTypeRef)(txtMob2.text), kABHomeLabel, NULL);
ABRecordSetValue(newPerson, kABPersonPhoneProperty, phone, &error);
//image
NSData *dataref = UIImagePNGRepresentation(imgProfile.image);
ABPersonSetImageData(newPerson, (__bridge CFDataRef)(dataref), &error);
ABAddressBookAddRecord(addressbook, newPerson, &error);
ABAddressBookSave(addressbook, nil);
CFRelease(newPerson);
// Now Below code is of displaying details.
- (void)displayContacts
{
int i;
appDelegate.arr_contact = [[NSMutableArray alloc] init];
ABAddressBookRef contactBook =ABAddressBookCreateWithOptions(nil, NULL);
NSArray *allData = (__bridge_transfer NSArray *)(ABAddressBookCopyArrayOfAllPeople(contactBook));
NSUInteger contactNum = 0;
NSInteger recordId;
ABRecordRef recId;
for (i =0; i < [allData count]; i++)
{
appDelegate.dict_contact =[[NSMutableDictionary alloc] init];
ABRecordRef ref =(__bridge ABRecordRef)(allData[i]);
//mobile no and phone no
ABMultiValueRef mobNum = ABRecordCopyValue(ref, kABPersonPhoneProperty);
CFIndex PhoneCount = ABMultiValueGetCount(mobNum);
for (int k = 0; k <PhoneCount; k++) {
strMobile = (__bridge NSString *)(ABMultiValueCopyLabelAtIndex(mobNum, k));
strPhone = (__bridge NSString *)(ABMultiValueCopyValueAtIndex(mobNum, k));
if ([strMobile isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
{
mobileno = (__bridge NSString*)ABMultiValueCopyValueAtIndex(mobNum, k);
}
else if ([strPhone isEqualToString:(NSString *)kABHomeLabel])
{
phoneno = (__bridge NSString*)ABMultiValueCopyValueAtIndex(mobNum, k);
break;
}
NSLog(#"Mobile: %# phone: %#, %#",mobileno, phoneno, strPhone);
[appDelegate.dict_contact setObject:[NSString stringWithFormat:#"%#",mobileno] forKey:#"mobno"];
[appDelegate.dict_contact setObject:[NSString stringWithFormat:#"%#",phoneno] forKey:#"phnno"];
}
//image
NSData *imgData = (__bridge NSData *)ABPersonCopyImageDataWithFormat(ref, kABPersonImageFormatThumbnail);
UIImage *image;
if (imgData)
{
image = [UIImage imageWithData:imgData];
NSLog(#"add image: %#",image);
}else
{
image = [UIImage imageNamed:#"dummy.png"];
}
[appDelegate.dict_contact setObject:image forKey:#"image"];
[appDelegate.arr_contact addObject:appDelegate.dict_contact];
}
}
Please check my edited code.
Please See this code....
-(void)GetAddressBook
{
Contacts = [[NSMutableArray alloc]init];
if (ABAddressBookCreateWithOptions) {
#try {
ABAddressBookRef addressBook = ABAddressBookCreate();
// NSArray *people = (NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);
if (!addressBook) {
NSLog(#"opening address book");
}
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
NSLog(#"opening address book ==%ld",nPeople);
for (int i=0;i < nPeople;i++) {
NSMutableDictionary *dOfPerson=[NSMutableDictionary dictionary];
ABRecordRef ref = CFArrayGetValueAtIndex(allPeople,i);
NSString *Contact;
ABMultiValueRef phones =(__bridge ABMultiValueRef)((__bridge NSString*)ABRecordCopyValue(ref, kABPersonPhoneProperty));
CFStringRef firstName, lastName;
NSMutableArray *array = [[NSMutableArray alloc]init];
NSString *email;
firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
lastName = ABRecordCopyValue(ref, kABPersonLastNameProperty);
ABMultiValueRef multiValueRef = ABRecordCopyValue(ref, kABPersonEmailProperty);
array = [(__bridge NSMutableArray *)ABMultiValueCopyArrayOfAllValues(multiValueRef) mutableCopy];
email = ([array count] > 0) ? array[0] : #"";
if(firstName)
{
Contact = [NSString stringWithFormat:#"%#", firstName];
if(lastName)
Contact = [NSString stringWithFormat:#"%# %#",firstName,lastName];
}
[dOfPerson setObject:Contact forKey:#"name"];
[dOfPerson setObject:[NSString stringWithFormat:#"%d", i] forKey:#"id"];
[dOfPerson setObject:[NSString stringWithFormat:#"%#",#""] forKey:#"found"];
[dOfPerson setObject:email forKey:#"email"];
NSString* mobileLabel;
for(CFIndex j = 0; j< ABMultiValueGetCount(phones); j++)
{
mobileLabel = (__bridge NSString*)ABMultiValueCopyLabelAtIndex(phones, j);
if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
{
[dOfPerson setObject:(__bridge NSString*)ABMultiValueCopyValueAtIndex(phones, j) forKey:#"Phone"];
}
else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel])
{
[dOfPerson setObject:(__bridge NSString*)ABMultiValueCopyValueAtIndex(phones, j) forKey:#"Phone"];
break ;
}
}
[Contacts addObject:dOfPerson];
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
}
dispatch_async(dispatch_get_main_queue(), ^{
});
Here you will get Phone number, First Name, Last name and Email Id. Here Contacts is an NSMutableArray. Also view this answer for a complete set of code.
contact details from ipad using objective-c
Try This In this code I'm getting both the name and mobile number if you want the mobile number only use this kABPersonPhoneProperty:
CFErrorRef * error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
for (int i=0;i < nPeople;i++)
{
NSString* name;
NSMutableDictionary* tempContactDic = [NSMutableDictionary new];
ABRecordRef ref = CFArrayGetValueAtIndex(allPeople,i);
CFStringRef firstName;
firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
name = (__bridge NSString *)(firstName);
[tempContactDic setValue:name forKey:#"name"];
//fetch email id
NSString *strEmail;
NSMutableString* strMobile;
ABMultiValueRef email = ABRecordCopyValue(ref, kABPersonPhoneProperty);
CFStringRef tempEmailref = ABMultiValueCopyValueAtIndex(email, 0);
strEmail = (__bridge NSString *)tempEmailref;
strEmail = [strEmail stringByReplacingOccurrencesOfString:#"-" withString:#""];
strEmail = [strEmail stringByReplacingOccurrencesOfString:#"(" withString:#""];
strEmail = [strEmail stringByReplacingOccurrencesOfString:#")" withString:#""];
strEmail = [strEmail stringByReplacingOccurrencesOfString:#" " withString:#""];
strEmail = [strEmail stringByReplacingOccurrencesOfString:#"+" withString:#""];
strMobile = [[NSMutableString alloc] initWithString:strEmail];
if ([strEmail length] == 10) {
[strMobile insertString:#"91" atIndex:0];
}
else {
}
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:strMobile];
[tempContactDic setValue:myNumber forKey:#"phone"];
[contactsArray addObject:tempContactDic];
}
/// With below two steps of code you'll get the contacts in alphabetical order
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"name" ascending:YES selector:#selector(localizedCaseInsensitiveCompare:)];
[contactsArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
I am using Addressbook in my IOS app to fetch the contact name and numbers, but a strange thing is happening that it is showing phone number of some of the contacts.
I was hoping it will show all the contact list with phone number.
so here is my code to fetch phone numbers:
-(void)getAddressbookData
{
#if __IPHONE_OS_VERSION_MIN_REQUIRED < 60000
ABAddressBookRef addressBook = ABAddressBookCreate();
#else
CFErrorRef *error = nil;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
#endif
NSArray * people;
BOOL accessGranted = [self __addressBookAccessStatus:addressBook];
if (accessGranted)
{
people = (__bridge_transfer NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);
// Do whatever you need with thePeople...
}
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
NSMutableArray *contactArray = [[NSMutableArray alloc] init];
for (CFIndex i = 0; i < nPeople; i++)
{
ABRecordRef record = CFArrayGetValueAtIndex((__bridge CFArrayRef)(people), i);
NSString *firstName = (__bridge NSString *)ABRecordCopyValue(record, kABPersonFirstNameProperty);
NSString *lastName = (__bridge NSString *)ABRecordCopyValue(record, kABPersonLastNameProperty);
NSString *fullName = nil;
if (ABPersonGetCompositeNameFormat() == kABPersonCompositeNameFormatFirstNameFirst)
fullName = [NSString stringWithFormat:#"%# %#", firstName, lastName];
else
fullName = [NSString stringWithFormat:#"%#, %#", lastName, firstName];
[contactArray addObject:fullName];
//
// Phone Numbers
//
ABMutableMultiValueRef phoneNumbers = ABRecordCopyValue(record, kABPersonPhoneProperty);
CFIndex phoneNumberCount = ABMultiValueGetCount( phoneNumbers );
NSMutableArray *numbersArray = [[NSMutableArray alloc] init];
for ( CFIndex k=0; k<phoneNumberCount; k++ )
{
CFStringRef phoneNumberLabel = ABMultiValueCopyLabelAtIndex( phoneNumbers, k );
CFStringRef phoneNumberValue = ABMultiValueCopyValueAtIndex( phoneNumbers, k );
CFStringRef phoneNumberLocalizedLabel = ABAddressBookCopyLocalizedLabel( phoneNumberLabel );
// converts "_$!<Work>!$_" to "work" and "_$!<Mobile>!$_" to "mobile"
// Find the ones you want here
//
// NSLog(#"-----PHONE ENTRY -> name:%# : %# : %#", fullName, phoneNumberLocalizedLabel, phoneNumberValue );
[numbersArray addObject:CFBridgingRelease(phoneNumberValue)];
CFRelease(phoneNumberLocalizedLabel);
CFRelease(phoneNumberLabel);
CFRelease(phoneNumberValue);
}
// NSLog(#"phone numbers %#", numbersArray);
[contactDictionary setObject:numbersArray forKey:fullName];
CFRelease(record);
}
selectContacts = contactArray;
// NSLog(#"dictionary of array %#", contactDictionary);
//NSLog(#"contacts count %d", [selectContacts count]);
}
-(BOOL)__addressBookAccessStatus:(ABAddressBookRef) addressBook
{
__block BOOL accessGranted = NO;
if (ABAddressBookRequestAccessWithCompletion != NULL) { // we're on iOS 6
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
accessGranted = granted;
dispatch_semaphore_signal(sema);
});
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
// dispatch_release(sema);
}
else { // we're on iOS 5 or older
accessGranted = YES;
}
return accessGranted;
}
so numbersArray is blank for some of the contacts I dont know why it is happening.
try this for phone no.
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *people = (NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);
for(id person in people){
//fetch multiple phone nos.
ABMultiValueRef multi = ABRecordCopyValue(person, kABPersonPhoneProperty);
for (CFIndex j=0; j < ABMultiValueGetCount(multi); j++) {
NSString* phone = (NSString*)ABMultiValueCopyValueAtIndex(multi, j);
[numbersArray addObject:phone];
[phone release];
}
}
and you have to alloc your array before you use. in viewDidLoad method write this for alloc array
numbersArray=[[NSMutableArray alloc] init];
I am using this code to access the mobile number from my address book and its working fine.
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef allSources = ABAddressBookCopyArrayOfAllPeople( addressBook );
for (CFIndex i = 0; i < ABAddressBookGetPersonCount( addressBook ); i++)
{
ABRecordRef aSource = CFArrayGetValueAtIndex(allSources,i);
ABMultiValueRef phones =(NSString*)ABRecordCopyValue(aSource, kABPersonPhoneProperty);
NSString* mobileLabel;
for(CFIndex i = 0; i < ABMultiValueGetCount(phones); i++) {
mobileLabel = (NSString*)ABMultiValueCopyLabelAtIndex(phones, i);
if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
{
home_mobile = [(NSString*)ABMultiValueCopyValueAtIndex(phones, i) retain];
}
if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel])
{
basic_mobile = [(NSString*)ABMultiValueCopyValueAtIndex(phones, i)retain];
}
if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMainLabel])
{
work_mobile = [(NSString*)ABMultiValueCopyValueAtIndex(phones, i)retain];
}
}
You can try this.
Here's the Swift version of #Samir's answer which worked for me.
var allNumbers: [AnyObject] = []
let adbk : ABAddressBook? = ABAddressBookCreateWithOptions(nil, nil).takeRetainedValue()
let people = ABAddressBookCopyArrayOfAllPeople(adbk).takeRetainedValue() as NSArray as [ABRecord]
for person in people {
var phones: ABMultiValueRef = ABRecordCopyValue(person, kABPersonPhoneProperty).takeRetainedValue()
for j in 0..<ABMultiValueGetCount(phones) {
var phone: String = ABMultiValueCopyValueAtIndex(phones, j).takeRetainedValue() as String
allNumbers.append(phone)
}
}
println(allNumbers)
+(NSMutableArray *)getLastName
{
ABAddressBookRef addressBook = ABAddressBookCreate();
NSMutableArray *lastNameArray = [[NSMutableArray alloc]init];
ABRecordRef source = ABAddressBookCopyDefaultSource(addressBook);
CFIndex numberOfContacts = ABAddressBookGetPersonCount(addressBook);
NSLog(#"%ld",numberOfContacts);
CFArrayRef people = (__bridge CFArrayRef)((__bridge NSArray*)ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, source, kABPersonSortByLastName));
NSArray * tempArray = [[NSArray alloc]init];
tempArray = (__bridge NSArray *)(people);
if ([tempArray count]>0) {
for (int personIndex = 0; personIndex < [tempArray count]-1; personIndex++) {
ABRecordRef person = (__bridge ABRecordRef)([tempArray objectAtIndex:personIndex]);
ABMultiValueRef lastName = ABRecordCopyValue(person, kABPersonLastNameProperty);
NSString *lastNameString = (__bridge NSString *)lastName;
if (lastName!=nil)
[lastNameArray addObject:lastNameString];
}
}
return lastNameArray;
}
I am using the xcode 6.0. iphone 3s is working fine but iphone 4s and iphone 5 not working in that code
-(void)_addContactToAddressBook
{
char *lastNameString, *firstNameString,*emailString;
NSMutableArray *arrname =[[NSMutableArray alloc] init];
NSMutableArray *arrTemp = [[NSMutableArray alloc] init];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
// AddressBook
ABAddressBookRef ab = ABAddressBookCreate();
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(ab);
CFIndex nPeople = ABAddressBookGetPersonCount(ab);
for(int i = 0; i < nPeople; i++)
{
[dict removeAllObjects];
ABRecordRef ref = CFArrayGetValueAtIndex(allPeople, i);
CFStringRef firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
CFStringRef lastName = ABRecordCopyValue(ref, kABPersonLastNameProperty);
ABMutableMultiValueRef multi = ABRecordCopyValue(ref, kABPersonEmailProperty);
CFStringRef email;
if (ABMultiValueGetCount(multi) > 0) {
// collect all emails in array
for (CFIndex i = 0; i < ABMultiValueGetCount(multi); i++)
{
CFStringRef emailRef = ABMultiValueCopyValueAtIndex(multi, i);
//[personDealingWithEmails addObject:(NSString *)emailRef];
email=emailRef;
CFRelease(emailRef);
}
}
else
{
email=nil;
}
CFDataRef imgData;
if(ABPersonHasImageData(ref))
{
imgData = ABPersonCopyImageData(ref);
}else {
imgData=nil;
}
static char* fallback = "";
int fbLength = strlen(fallback);
int firstNameLength = fbLength;
bool firstNameFallback = true;
int lastNameLength = fbLength;
bool lastNameFallback = true;
int emailLength = fbLength;
bool emailFallback = true;
if (firstName != NULL)
{
firstNameLength = (int) CFStringGetLength(firstName);
firstNameFallback = false;
}
if (lastName != NULL)
{
lastNameLength = (int) CFStringGetLength(lastName);
lastNameFallback = false;
}
if (email != NULL)
{
emailLength = (int) CFStringGetLength(email);
emailFallback = false;
}
if (firstNameLength == 0)
{
firstNameLength = fbLength;
firstNameFallback = true;
}
if (lastNameLength == 0)
{
lastNameLength = fbLength;
lastNameFallback = true;
}
if (emailLength == 0)
{
emailLength = fbLength;
emailFallback = true;
}
firstNameString = malloc(sizeof(char)*(firstNameLength+1));
lastNameString = malloc(sizeof(char)*(lastNameLength+1));
emailString = malloc(sizeof(char)*(emailLength+1));
if (firstNameFallback == true)
{
strcpy(firstNameString, fallback);
}
else
{
CFStringGetCString(firstName, firstNameString, 10*CFStringGetLength(firstName), kCFStringEncodingASCII);
}
if (lastNameFallback == true)
{
strcpy(lastNameString, fallback);
}
else
{
CFStringGetCString(lastName, lastNameString, 10*CFStringGetLength(lastName), kCFStringEncodingASCII);
}
if (emailFallback == true)
{
strcpy(emailString, fallback);
}
else
{
CFStringGetCString(email, emailString, 10*CFStringGetLength(email), kCFStringEncodingASCII);
}
printf("%d.\t%s %s\n", i, firstNameString, lastNameString);
NSString *fname= [NSString stringWithFormat:#"%s",firstNameString];
NSString *lname= [NSString stringWithFormat:#"%s",lastNameString];
NSString *fullName=[NSString stringWithFormat:#"%#%#%#",fname,([fname length]!=0)?#" ":#"",lname];
NSString *eMail= [NSString stringWithFormat:#"%s",emailString];
NSData *myData;
if (imgData) {
myData=(__bridge NSData *)imgData;
}else {
myData=nil;
}
//fetch Phone num
ABMultiValueRef phoneNumberProperty = ABRecordCopyValue(ref, kABPersonPhoneProperty);
NSArray* phoneNumbers = (__bridge NSArray*)ABMultiValueCopyArrayOfAllValues(phoneNumberProperty);
CFRelease(phoneNumberProperty);
// Do whatever you want with the phone numbers
//NSLog(#"Phone numbers = %#", phoneNumbers);
NSString *PhoneNum = [phoneNumbers objectAtIndex:0];
//--------------remove special char form string(Phone number)-----------------
NSString *originalString = PhoneNum;
//NSLog(#"%#", originalString);
NSMutableString *strippedString = [NSMutableString
stringWithCapacity:originalString.length];
NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet
characterSetWithCharactersInString:#"0123456789"];
while ([scanner isAtEnd] == NO) {
NSString *buffer;
if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
[strippedString appendString:buffer];
} else {
[scanner setScanLocation:([scanner scanLocation] + 1)];
}
}
if([fname isEqualToString:#""] && [lname isEqualToString:#""]){
}else{
if (myData) {
UIImage *img = [UIImage imageWithData:myData];
[dict setObject:img forKey:#"imgData"];
}
[dict setValue:fname forKey:#"fname"];
[dict setValue:lname forKey:#"lname"];
[dict setValue:fullName forKey:#"fullName"];
[dict setValue:eMail forKey:#"email"];
[dict setValue:strippedString forKey:#"phoneNumber"];
[dict setValue:#"addressbook" forKey:#"type"];
[arrname addObject:[dict copy]];
}
if (firstName != NULL)
{
CFRelease(firstName);
}
if (imgData != NULL)
{
CFRelease(imgData);
}
if (lastName != NULL)
{
CFRelease(lastName);
}
if (email != NULL)
{
CFRelease(email);
}
free(firstNameString);
free(lastNameString);
free(emailString);
}
for (int i=0; i<[arrname count]; i++)
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
[dict setValue:#"0" forKey:#"sel"];
[arrTemp addObject:dict];
}
[arrallcontacts addObjectsFromArray:arrname];
[arraddedcontactsfulllist addObjectsFromArray:arrallcontacts];
NSSortDescriptor *sortByfullName = [[NSSortDescriptor alloc] initWithKey:#"fullName" ascending:YES];
NSArray *descriptors = [NSArray arrayWithObject:sortByfullName];
NSArray *sorted = [arraddedcontactsfulllist sortedArrayUsingDescriptors:descriptors];
[arraddedcontactsfulllist removeAllObjects];
[arraddedcontactsfulllist addObjectsFromArray:sorted];
[arraddedcontacts removeAllObjects];
[arraddedcontacts addObjectsFromArray:sorted];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1];
tblview.alpha=1;
[UIView commitAnimations];
[tblview reloadData];
if (![[[[NSUserDefaults standardUserDefaults] objectForKey:#"USER_DETAIL"] objectForKey:#"facebook"] isEqualToString:#"Unauthenticate"]) {
[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
[self performSelector:#selector(getfacebookfriends) withObject:nil afterDelay:0.0001];
}
}
-(void)fetchIphoneContact
{
if ([[UIDevice currentDevice].systemVersion floatValue]>=6.0)
{
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
// First time access has been granted, add the contact
[self _addContactToAddressBook];
[tblview reloadData];
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
// The user has previously given access, add the contact
[self _addContactToAddressBook];
[tblview reloadData];
}
else {
// The user has previously denied access
// Send an alert telling user to change privacy setting in settings app
DisplayAlertWithTitle(APP_Name, #"You can change your privacy setting in settings app");
}
}
else
{
[self _addContactToAddressBook];
}
}
This will work on iOS6 and lower..
I think the problem is with you iOS version.... If you're using iOS 6.0 then ABAddressBookCreate() won't work... it is fine for iOS 5.1 or before.... so you can do like,
ABAddressBookRef addressBook;
if ([self isABAddressBookCreateWithOptionsAvailable])
{
// iOS 6
CFErrorRef error = nil;
addressBook = ABAddressBookCreateWithOptions(NULL,&error);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error)
{
});
ABAddressBookRevert(addressBook);
}
else
{
// iOS 4/5
addressBook = ABAddressBookCreate();
}
-(BOOL)isABAddressBookCreateWithOptionsAvailable
{
return &ABAddressBookCreateWithOptions != NULL;
}
By this you can get all contacts...:)
There could be different ways to retrieve AddressBook in IOS but one way which I use to retrieve addressbook is as follows, make sure you are using ABPeoplePickerNavigationControllerDelegate You can open the AddressBook Controller on a button click like this
-(IBAction)getContact:(id)sender {
// creating the picker
ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
// place the delegate of the picker to the controll
picker.peoplePickerDelegate = self;
[self presentModalViewController:picker animated:YES];
}
after addressBook is presented you can use the delegate methods to receive the contact information as follows
- (BOOL)peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person {
// setting the first name
firstNameTxt.text = (__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
// setting the last name
lastNameTxt.text = (__bridge NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
// setting the number
/*
this function will set the first number it finds
if you do not set a number for a contact it will probably
crash
*/
ABMultiValueRef multi = ABRecordCopyValue(person, kABPersonPhoneProperty);
telefonTxt.text = (__bridge NSString*)ABMultiValueCopyValueAtIndex(multi, 0);
ABMultiValueRef multi1 = ABRecordCopyValue(person, kABPersonEmailProperty);
emailTxt.text = (__bridge NSString*)ABMultiValueCopyValueAtIndex(multi1, 0);
// remove the controller
[self dismissModalViewControllerAnimated:YES];
return NO;
}
I have tried this but it crashes:
- (NSDictionary *)contacts {
NSMutableArray *result = [NSMutableArray array];
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFRelease(addressBook);
NSArray *peopleArray = (NSArray *)people;
// Return if there are no contacts in the address book
if (peopleArray && peopleArray.count > 0) {
for (int i = 0; i <= peopleArray.count - 1; i++) {
ABRecordRef person = [peopleArray objectAtIndex:i];
ABRecordID sourceID = ABRecordGetRecordID(person);
ABMutableMultiValueRef multiEmail = ABRecordCopyValue(person, kABPersonEmailProperty);
NSString *emailAddress = (NSString *) ABMultiValueCopyValueAtIndex(multiEmail, 0); //EXE BAD ACCESS
[emailAddress release];
CFRelease(multiEmail);
NSLog(#"email address %#", emailAddress);
NSString *sourceId = [NSString stringWithFormat:#"%i", sourceID];
NSLog(#"%#", sourceId);
}
}
if (peopleArray) CFRelease(people);
return [NSArray arrayWithArray:result];
}
Try not to release addressBook until you have done. I had a similar problem and that fixed the issue.