升到 iOS 6 之後,一些原本工作正常的通訊錄相關應用突然出錯,表現有兩個:啟動時不再彈出「是否允許訪問通訊錄」的提示,同時「設置 → 隱私 → 通訊錄」列表里也找不到你的應用。操作通訊錄的代碼則會拋出類似下面的錯誤:
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 提出申請,系統才會彈窗並把應用登記到隱私列表里。少了這一步,AddressBook 的查詢自然無法完成。
通常把這段邏輯放在程序啟動階段,讓用戶在早期就完成授權:
ABAddressBookRef addressBook = ABAddressBookCreate();
__block BOOL accessGranted = NO;
if (ABAddressBookRequestAccessWithCompletion != NULL) {
// 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 {
// iOS 5 及更早,無需申請
accessGranted = YES;
}
if (accessGranted) {
NSLog(@"we got the access right");
}
這裡用信號量把異步回調同步化,是為了在啟動流程里拿到確定結果。若無需在啟動時阻塞,也可以把後續邏輯直接寫進 completion block,代碼更自然。另外別忘了 CFRelease(addressBook) 釋放 CF 對象。
官方說明可查:https://developer.apple.com/library/ios/#releasenotes/General/RN-iOSSDK-6_0/index.html