如何在ios 7中授予访问手机地址簿的权限?

时间:2014-05-12 11:18:03

标签: ios objective-c ios7 abaddressbook

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)
    {

    }

以上代码在模拟器中工作正常,但是当我在Iphone 5c中运行应用程序时,它并没有要求我的许可,而且我无法从设备地址簿中获取电话号码。

帮我解决这个问题。 提前谢谢。

1 个答案:

答案 0 :(得分:3)

viewDidLoad方法

中调用此行
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
}