我忍受了好幾天,試圖訪問名稱和電話號碼簿,全部失敗。我使用了以下代碼,該代碼在測試應用程序中成功運行,但是當我將它添加到項目工作中時,它不起作用。 「授予」變量不斷具有值 - 「錯誤」,並且出現「訪問失敗」錯誤。儘管如此,在隱私設置不顯示滑塊允許訪問... 我早已找不到的答案,一個相當奇怪的行爲...應用程序無法訪問電話簿
我會感謝任何幫助!`
CNContactStore *store = [[CNContactStore alloc] init];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted == YES) {
NSMutableArray *contacts = [NSMutableArray array];
NSArray *keys = @[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey];
NSString *containerId = store.defaultContainerIdentifier;
NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
NSError *error;
NSArray *cnContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
if (error) {
NSLog(@"error fetching contacts %@", error);
} else {
for (CNContact *contact in cnContacts) {
TSContact *newContact = [[TSContact alloc] init];
newContact.firstName = contact.givenName;
newContact.lastName = contact.familyName;
UIImage *image = [UIImage imageWithData:contact.imageData];
newContact.image = image;
for (CNLabeledValue *label in contact.phoneNumbers) {
NSString *phone = [label.value stringValue];
if ([phone length] > 0) {
[contacts addObject:phone];
}
}
}
}
} else {
NSLog(@"Error = %@", error.localizedDescription);
}
}];
什麼是您的應用程序的部署目標(目標iOS版本6.0的東西)? – theFool
您是否在info.plist中添加了「隱私 - 聯繫人使用說明」鍵?它支持iOS 6.0及更高版本。 –
我試過iOS ios 8和9仍然不起作用 –