如何使用Objective C在我的应用程序中获取联系人图像和电话号码

时间:2015-12-28 11:36:57

标签: ios objective-c contacts cncontact

我从手机上获取联系人姓名。 检查我的代码:

- (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中是否可行?

给我建议

谢谢。

4 个答案:

答案 0 :(得分:2)

获取联系人的图像很容易。我认为您要在表格视图中显示联系人的图像以及名称。如果是,则将每个联系人的数据存储在数据源数组中作为词典。

    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];
    }

在您的cellForRowAtIndexPath:方法中,相应地使用字典。

答案 1 :(得分:1)

+ (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;
}

答案 2 :(得分:0)

  - (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;
}
}

答案 3 :(得分:0)

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.