问题
I am getting the contact name from my phone. Check my code:
- (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];
}];
}
for this code, I am getting the response
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
my requirement is I need to display the image and phone number of a particular contact in my app contacts page.
So is this possible in iOS 9?
give me suggestions
Thank you.
回答1:
Fetching the image of the contact is easy. I think that you want to show the image of the contact along with the name in the table view. If so, then store each contact's data in your data source array as dictionaries.
for (CNContact *contact in contacts) {
if (!_contacts) {
_contacts = [[NSMutableArray alloc] init];
}
NSArray<CNLabeledValue<CNPhoneNumber*>*> *phoneNumbers = contact.phoneNumbers;
CNPhoneNumber *phone = [phoneNumbers[0] value];
NSMutableDictionary *dictionary = [NSMutableDictionary new];
NSString *nameString = contact.givenName;
[dictionary setValue:nameString forKey:@"name"];
NSString *phoneString = phone.stringValue;
[dictionary setValue:phoneString forKey:@"phone"];
if (contact.imageDataAvailable) {
[dictionary setValue:self.contactToAdd.imageData forKey:@"image"];
}
NSLog(@"contact = %@", contact);
[_contacts addObject:dictionary];
}
And in your cellForRowAtIndexPath:
method use the dictionary accordingly.
回答2:
+ (UIImage *)getImageForContactIdentifier:(NSString *)contactIdentifer
{
NSError *error;
NSArray *keysToFetch = @[CNContactImageDataAvailableKey, CNContactThumbnailImageDataKey];
CNContact *contact = [[NWContactManager sharedManger].contactStore unifiedContactWithIdentifier:contactIdentifer keysToFetch:keysToFetch error:&error];
UIImage *image;
if (contact.imageDataAvailable) {
image = [UIImage imageWithData:contact.thumbnailImageData];
}
return image;
}
//For iOS8 or below, Use Following code
+ (UIImage *)getImageForContactIdentifier:(NSNumber *)contactIdentifer
{
CFErrorRef error = NULL;
ABRecordID recId = (ABRecordID)[contactIdentifer intValue];
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
ABRecordRef contactPerson = ABAddressBookGetPersonWithRecordID(addressBook, recId);
UIImage *image;
CFDataRef imageData = ABPersonCopyImageData(contactPerson);
if (imageData) {
image = [UIImage imageWithData:(__bridge NSData *)imageData];
}
return image;
}
回答3:
- (UIImage *) contactPicture:(NSInteger)contactId {
// Get contact from Address Book
ABAddressBookRef addressBook = ABAddressBookCreate();
ABRecordID recordId = (ABRecordID)[contactId intValue];
ABRecordRef person = ABAddressBookGetPersonWithRecordID(addressBook, recordId);
// Check for contact picture
if (person != nil && ABPersonHasImageData(person)) {
if ( &ABPersonCopyImageDataWithFormat != nil ) {
// iOS >= 4.1
return [UIImage imageWithData:(NSData *)ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatThumbnail)];
} else {
// iOS < 4.1
return [UIImage imageWithData:(NSData *)ABPersonCopyImageData(person)];
}
} else {
return nil;
}
}
回答4:
for (CNContact *contact in contacts) {
if (!contacts) {
contacts = [[NSMutableArray alloc] init];
if ( contact.imageData != nil ) {
// iOS >= 4.1
UIImage *CIMage = [UIImage imageWithData:(NSData *)contact.imageData];
}
}
NSString *string = [formatter stringFromContact:contact];
NSLog(@"contact = %@", string);
[contacts addObject:string];
}
// Please this code is run in my app please try it.
来源:https://stackoverflow.com/questions/34492804/how-to-fetch-contact-image-and-phone-number-in-my-app-using-objective-c