I have an app that is accessing the address book. The app programatically accesses the address book on viewDidLoad, pulls all of the contacts, and places their first names into an NSString object called firstName.
For some reason, if I stop using the app, add a new contact to the address book, and then start running the app again it shows that new contact's first name as null.
I looked at all of the contacts that have been working, and compared them to the new contacts I am adding in, and nothing is different. They all have "mobile" numbers and a first name.
But no matter how many new contacts I add, all of their first names print to the console as null.
Here is the code I am using:
ABAddressBookRef m_addressbook = ABAddressBookCreateWithOptions(NULL, NULL);
ABAddressBookCopyArrayOfAllPeople(m_addressbook);
__block BOOL accessGranted = NO;
if (ABAddressBookRequestAccessWithCompletion != NULL) { // we're on iOS 6
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
@autoreleasepool {
// Write your code here...
// Fetch data from SQLite DB
}
});
ABAddressBookRequestAccessWithCompletion(m_addressbook, ^(bool granted, CFErrorRef error)
{
accessGranted = granted;
NSLog(@"Has access been granted?: %hhd", accessGranted);
NSLog(@"Has there been an error? %@", error);
dispatch_semaphore_signal(sema);
});
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}
else { // we're on iOS 5 or older
accessGranted = YES;
}
if (accessGranted) {
NSArray *allContacts = (__bridge_transfer NSArray
*)ABAddressBookCopyArrayOfAllPeople(m_addressbook);
int z = allContacts.count - 1;
for (int i = 0; i < z; i++)
{
NSArray *allContacts = (__bridge_transfer NSArray
*)ABAddressBookCopyArrayOfAllPeople(m_addressbook);
ABRecordRef contactPerson = (__bridge ABRecordRef)allContacts[i];
NSString *firstName = (__bridge_transfer NSString
*)ABRecordCopyValue(contactPerson, kABPersonFirstNameProperty);
NSLog(@"FIRSTNAME: %@", firstName);
When it gets to the very last statement, NSLog(@"FIRSTNAME: %@", firstName);
, all of the contacts' first names print correctly, except for any new ones that were just added.
I even ran a test, and deleted a contact that was working, and then re-added them exactly as they were, and sure enough they are now NSLogging with a null first name value.