我苦苦挣扎了好几天,试图访问电话簿的姓名和号码,但都失败了。我使用以下代码,它在测试应用程序中成功运行,但是当我将它添加到您的项目工作中时,它不起作用。变量“granted”不断有一个值 - “false”,我收到错误“访问失败”。尽管如此,在隐私设置中没有显示滑块以允许访问......我早就找不到一个相当奇怪的行为的答案......
如有任何帮助,我将不胜感激!`
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);
}
}];