iOS6 中如何获得通讯录访问权限

来源:互联网 发布:vscode插件 web前端 编辑:程序博客网 时间:2024/05/16 02:00

在iOS 6中,以前工作正常的访问通讯录的iPhone程序可能会出错,现象是程序启动时不提醒用户是否允许程序访问通讯录,同时在“设置->隐私->通讯录”中看不到你的程序。另外,对通讯录进行操作的代码会报类似于以下消息的错误:


Could not compile statement for query (ABCCopyArrayOfAllInstancesOfClassInSourceMatchingProperties):SELECT ROWID, Name, ExternalIdentifier, Type, ConstraintsPath, ExternalModificationTag, ExternalSyncTag, AccountID, Enabled, SyncData, MeIdentifier, Capabilities FROM ABStore WHERE Enabled = ?;

其原因是iOS 6加强了通讯录访问控制,要求开发人员显式声明需要访问通讯录,方法是调用 ABAddressBookRequestAccessWithCompletion

方法,具体参见官方文档:

http://developer.apple.com/library/ios/#releasenotes/General/RN-iOSSDK-6_0/index.html


下面是对应的样例代码,一般来讲需要将这段代码放置在程序启动部分,在程序启动过程中提示用户本程序需要访问设备上的通讯录:

ABAddressBookRef addressBook = ABAddressBookCreate();                    __block BOOL accessGranted = NO;    if (ABAddressBookRequestAccessWithCompletion != NULL) {                // we're on iOS 6        NSLog(@"on iOS 6 or later, trying to grant access permission");                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                NSLog(@"on iOS 5 or older, it is OK");        accessGranted = YES;    }        if (accessGranted) {                NSLog(@"we got the access right");    }    


原创粉丝点击