我正在从手机中获取联系人姓名。检查我的代码:
- (void) fetchContacts
{
CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
if (status == CNAuthorizationStatusDenied || status == CNAuthorizationStatusDenied) {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"This app previously was refused permissions to contacts; Please go to settings and grant permission to this app so it can use contacts" preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
[self presentViewController:alert animated:TRUE completion:nil];
return;
}
CNContactStore *store = [[CNContactStore alloc] init]; [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
// make sure the user granted us access
if (!granted) {
dispatch_async(dispatch_get_main_queue(), ^{
// user didn't grant access;
// so, again, tell user here why app needs permissions in order to do it's job;
// this is dispatched to the main queue because this request could be running on background thread
});
return;
}
// build array of contacts
NSMutableArray *contacts = [NSMutableArray array];
NSError *fetchError;
CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:@[CNContactIdentifierKey, [CNContactFormatter descriptorForRequiredKeysForStyle:CNContactFormatterStyleFullName]]];
BOOL success = [store enumerateContactsWithFetchRequest:request error:&fetchError usingBlock:^(CNContact *contact, BOOL *stop) {
[contacts addObject:contact];
}];
if (!success) {
NSLog(@"error = %@", fetchError);
}
// you can now do something with the list of contacts, for example, to show the names
CNContactFormatter *formatter = [[CNContactFormatter alloc] init];
for (CNContact *contact in contacts) {
if (!_contacts) {
_contacts = [[NSMutableArray alloc] init];
}
NSString *string = [formatter stringFromContact:contact];
NSLog(@"contact = %@", string);
[_contacts addObject:string];
}
[_contactatableview reloadData];
}];
}
对于这段代码,我得到了响应
2015-12-28 15:18:13.867 finalprototype[2138:66648] contact = John Appleseed
2015-12-28 15:18:13.868 finalprototype[2138:66648] contact = Kate Bell
2015-12-28 15:18:13.868 finalprototype[2138:66648] contact = Anna Haro
2015-12-28 15:18:13.868 finalprototype[2138:66648] contact = Daniel Higgins Jr.
2015-12-28 15:18:13.868 finalprototype[2138:66648] contact = David Taylor
2015-12-28 15:18:13.868 finalprototype[2138:66648] contact = Hank M. Zakroff
我的要求是我需要在我的应用程序联系人页面中显示特定联系人的图像和电话号码。
那么这在 iOS 9 中可能吗?
给我建议
谢谢你。