Programmatically Request Access to Contacts
For contacts framework:
- (void)checkPermissionForCNContacts
{
switch ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts])
{
case CNAuthorizationStatusNotDetermined:
{
[[[CNContactStore alloc] init] requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted == YES)
[self showCNContactPicker];
}];
}
break;
case CNAuthorizationStatusRestricted:
case CNAuthorizationStatusDenied:
// Show custom alert
break;
case CNAuthorizationStatusAuthorized:
[self showCNContactPicker];
break;
}
}
As per this documentation on apple's site (scroll down to Privacy in the middle of the page), access to the address book must be granted before it can be access programmatically. Here is what I ended up doing.
#import <AddressBookUI/AddressBookUI.h>
// Request authorization to Address Book
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
if (granted) {
// First time access has been granted, add the contact
[self _addContactToAddressBook];
} else {
// User denied access
// Display an alert telling user the contact could not be added
}
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
// The user has previously given access, add the contact
[self _addContactToAddressBook];
}
else {
// The user has previously denied access
// Send an alert telling user to change privacy setting in settings app
}
Update For iOS 9 and later:
From Apple website :
Important
The Address Book UI framework is deprecated in iOS 9. Use the APIs defined in the ContactsUI framework instead. To learn more, see ContactsUI
ABAddressBookRef addressBook = ABAddressBookCreate();
__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;
}
if (accessGranted) {
if(self.isContactsChanged)
{
{
self.isContactsChanged=NO;
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
ABAddressBookRegisterExternalChangeCallback(addressBook, addressBookChanged, self);
int allPeopleCount = CFArrayGetCount(allPeople);
NSMutableArray *contactArrTemp = [[NSMutableArray alloc]init];
__block int noNumberCount=1;
managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
newMoc = [[NSManagedObjectContext alloc] init];
[newMoc setPersistentStoreCoordinator:[[AppDelegate getAppDelegate] persistentStoreCoordinator]];
[self DeleteAllPhoneContact];
NSNotificationCenter *notify = [NSNotificationCenter defaultCenter];
[notify addObserver:self
selector:@selector(mergeChanges:)
name:NSManagedObjectContextDidSaveNotification
object:newMoc];
self.backgroundQueue = dispatch_queue_create("com.storephonecontacts.bgqueue", NULL);
__block NSMutableDictionary *dic;
__block NSString *strTime,*strName,*strMobile,*strEmail,*strNotes;
__block NSDate *nsDate;
dispatch_async(self.backgroundQueue, ^{
NSMutableDictionary *dict =nil;
for (int i = 0; i < allPeopleCount; i++)
{
dic = [[NSMutableDictionary alloc]init];
ABRecordRef record = CFArrayGetValueAtIndex(allPeople,i);
NSDate *date = (NSDate*)ABRecordCopyValue(record, kABPersonCreationDateProperty);
nsDate = [date retain];
NSDateFormatter *formatterTime = [[NSDateFormatter alloc] init];
[formatterTime setDateFormat:@"hh.mm"];
NSString *dateStrPhone = [formatterTime stringFromDate:date];
strTime = [dateStrPhone retain];
[formatterTime release];
NSString *name = (NSString*)ABRecordCopyValue(record, kABPersonFirstNameProperty);
if([name length]>0)
name = [name stringByAppendingString:@" "];
NSString *name1 = (NSString*)ABRecordCopyValue(record, kABPersonLastNameProperty);
if([name1 length]>0)
{
if([name length]>0)
name = [name stringByAppendingString:name1];
else
name = (NSString*)ABRecordCopyValue(record, kABPersonLastNameProperty);
}
if([name length]>0)
strName = [name retain];
else
strName = [@"noName" retain];
//to save notes
NSString *notes = (NSString*)ABRecordCopyValue(record, kABPersonNoteProperty);
if(notes == NULL){
strNotes = @"noNotes";
}
else{
strNotes = [notes retain];
}
//for image
if (!ABPersonHasImageData(record)){
}
else{
CFDataRef imageData = ABPersonCopyImageData(record);
UIImage *image = [UIImage imageWithData:(NSData *) imageData];
[dic setObject:image forKey:@"image"];
CFRelease(imageData);
}
//To set Mobile
NSMutableArray* mobileArray = [[NSMutableArray alloc] init];
ABMutableMultiValueRef multi = ABRecordCopyValue(record, kABPersonPhoneProperty);
if (ABMultiValueGetCount(multi) > 0) {
// collect all emails in array
for (CFIndex i = 0; i < ABMultiValueGetCount(multi); i++) {
CFStringRef mobileRef = ABMultiValueCopyValueAtIndex(multi, i);
CFStringRef locLabel = ABMultiValueCopyLabelAtIndex(multi, i);
NSString *phoneLabel =(NSString*) ABAddressBookCopyLocalizedLabel(locLabel);
if([phoneLabel isEqualToString:@"mobile"])
[mobileArray addObject:(NSString *)mobileRef];
else if([phoneLabel isEqualToString:@"iPhone"])
[mobileArray addObject:(NSString *)mobileRef];
else if([phoneLabel isEqualToString:@"home"])
[mobileArray addObject:(NSString *)mobileRef];
else if([phoneLabel isEqualToString:@"work"])
[mobileArray addObject:(NSString *)mobileRef];
else if([phoneLabel isEqualToString:@"main"])
[mobileArray addObject:(NSString *)mobileRef];
else if([phoneLabel isEqualToString:@"other"])
[mobileArray addObject:(NSString *)mobileRef];
CFRelease(mobileRef);
CFRelease(locLabel);
}
}
CFRelease(multi);
if([mobileArray count]>0)
strMobile = [[mobileArray objectAtIndex:0]retain];
else{
NSString *str=[NSString stringWithFormat:@"noNumber%i",noNumberCount];
strMobile = [str retain];
noNumberCount++;
}
[mobileArray release];
//To set E-mail
NSMutableArray* emailArray = [[NSMutableArray alloc] init];
multi = ABRecordCopyValue(record, kABPersonEmailProperty);
if (ABMultiValueGetCount(multi) > 0) {
// collect all emails in array
for (CFIndex i = 0; i < ABMultiValueGetCount(multi); i++) {
CFStringRef emailRef = ABMultiValueCopyValueAtIndex(multi, i);
[emailArray addObject:(NSString *)emailRef];
CFRelease(emailRef);
}
}
CFRelease(multi);
if([emailArray count]>0)
strEmail = [[emailArray objectAtIndex:0]retain];
else
strEmail = [@"noemail" retain];
[emailArray release];
bool addBool = NO;
if([strName isEqualToString:@"noName"]){
if([strEmail isEqualToString:@"noemail"]){
}
else{
[dic setObject:strEmail forKey:@"name"];
addBool = YES;
}
if(addBool == NO){
if([strMobile isEqualToString:@"noNumber"]){
}
else{
[dic setObject:strMobile forKey:@"name"];
addBool = YES;
}
}
}
else{
[dic setObject:strName forKey:@"name"];
addBool = YES;
}
[dic setObject:strEmail forKey:@"email"];
[dic setObject:strMobile forKey:@"mobile"];
[dic setObject:nsDate forKey:@"date"];
[dic setObject:strTime forKey:@"time"];
[dic setObject:strNotes forKey:@"notes"];
if(addBool == YES)
[contactArrTemp addObject:dic];
if([strMobile hasPrefix:@"0"]){
NSString *contactNumber=[strMobile stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:@""];
if(contactNumber.length>7)
[dic setObject:@"iPhone" forKey:@"ContactType"];
}
else {
if(strMobile.length>9)
[dic setObject:@"iPhone" forKey:@"ContactType"];
}
if(![[dic objectForKey:@"ContactType"] isKindOfClass:[NSNull class]] && [dic objectForKey:@"ContactType"])
{
[self InsertContactWithContactInfoDictionary:dic];
}
[strName release];
[nsDate release];
[strEmail release];
[strMobile release];
[strTime release];
[strNotes release];
[dic release];
}
dispatch_async(self.backgroundQueue, ^(void){ [self gcdDidFinishaddfebriteParsing:dict]; });
dispatch_release(self.backgroundQueue);
self.backgroundQueue=nil;
});
}
}
else
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"PhoneContactsSaved" object:nil userInfo:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:@"Successful"]];
[[NSNotificationCenter defaultCenter] postNotificationName:@"updateContacts" object:nil userInfo:[NSDictionary dictionaryWithObject:@"success" forKey:@"update"]];
}
}
That did the perfect trick for me!
On iOS6, apple introduce new privacy control, user can control the accessment of contact and calender by each app. So, in the code side, you need to add some way to request the permission. In iOS5 or before, we can always call
ABAddressBookRef addressBook = ABAddressBookCreate();
to get the addressbook without any problem, but in iOS6, if you don't have permission, this call will just return empty pointer. That why we need to change the method to get ABAddressBookRef.
__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;
}
if (accessGranted) {
// Do whatever you want here.
}
In the code,semaphore is used for blocking until response, while ABAddressBookRequestAccessWithCompletion will ask for permission if the app didn't ask before. Otherwise it will just follow the settings in Settings-Privacy-Contact.
SOURCE: http://programmerjoe.blogspot.com/2012/10/ios6-permissions-contacts.html