Nirav Patadiya
Nirav Patadiya

Reputation: 97

How to give permission to access phone Addressbook in ios 7?

NSMutableArray *arrContacts=[[NSMutableArray alloc]init];


    CFErrorRef *error = nil;

    ABAddressBookRef addressbook = ABAddressBookCreateWithOptions(NULL, error);

    __block BOOL accessGranted = NO;

    if (ABAddressBookRequestAccessWithCompletion != NULL) { // we are used on the 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(addressbook, ^(bool granted, CFErrorRef error) {
            accessGranted = granted;
            dispatch_semaphore_signal(sema);
        });
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    }
    else { // we're on iOS 5 or older
        accessGranted = YES;
    }
    if (accessGranted)
    {

    }

Above code working fine in simulator but when i run the application in Iphone 5c it is not asking me for permission and i'm not able to get phone numbers from device addressbook.

help me to solve this issue. Thanks in advance.

Upvotes: 0

Views: 1759

Answers (1)

Anbu.Karthik
Anbu.Karthik

Reputation: 82759

call this line in your viewDidLoad method

ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(nil, nil);

if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
    ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
        if (granted) {
            // If the app is authorized to access the first time then add the contact

        } else {
            // Show an alert here if user denies access telling that the contact cannot be added because you didn't allow it to access the contacts
        }
    });
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
    // If the user user has earlier provided the access, then add the contact

}
else {
    // If the user user has NOT earlier provided the access, create an alert to tell the user to go to Settings app and allow access
}

Upvotes: 3

Related Questions