guru guru - 5 months ago 82
iOS Question

App is Not asking contact permission to access contact in iOS 9

I am using The Following code for getting iPhone Contacts but my App is not getting Permission For Allow Contacts in iOS 9 . I have found this code from stack and the other references are also same .

- (void)getPersonOutOfAddressBook
{
//1
CFErrorRef error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);

if (addressBook != nil) {
NSLog(@"Succesful.");

//2
NSArray *allContacts = (__bridge_transfer NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);

//3
NSUInteger i = 0; for (i = 0; i < [allContacts count]; i++)
{
NSMutableDictionary *persiondict =[[NSMutableDictionary alloc]init] ;
// Person *person = [[Person alloc] init];
ABRecordRef contactPerson = (__bridge ABRecordRef)allContacts[i];

//4
NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson,
kABPersonFirstNameProperty);
NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson, kABPersonLastNameProperty);
NSString *fullName = [NSString stringWithFormat:@"%@ %@", firstName, lastName];

// person.firstName = firstName;
// person.lastName = lastName;
// person.fullName = fullName;
[persiondict setValue:fullName forKey:@"fullName"] ;

//email
//5
ABMultiValueRef emails = ABRecordCopyValue(contactPerson, kABPersonEmailProperty);

//6
NSUInteger j = 0;
for (j = 0; j < ABMultiValueGetCount(emails); j++) {
NSString *email = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(emails, j);
if (j == 0) {
// person.homeEmail = email;
[persiondict setValue:email forKey:@"email"] ;

// NSLog(@"person.homeEmail = %@ ", person.homeEmail);
}
else if (j==1)
[persiondict setValue:email forKey:@"email"] ;

}

//7
[ArrUserOfContacts addObject:persiondict];
}

//8
CFRelease(addressBook);
} else {
//9
NSLog(@"Error reading Address Book");
}
}


I am unable to find problem here , How can user get an permission for access contacts . Any Suggestion Will be helpfull .

Answer

You need request permissions using ABAddressBookRequestAccessWithCompletion()

ABAddressBookRequestAccessWithCompletion(ABAddressBookCreateWithOptions(NULL, nil), ^(bool granted, CFErrorRef error) {
  if (!granted){
    //4
    NSLog(@"Just denied");
    return; 
  }
  //5
  NSLog(@"Just authorized");
});
Comments