如何在您的 iOS 应用中获取联系人 ID?

How to fetch contact id in your iOS app?

我是 iOS 的新手,我已经在我的应用程序中获取了联系人,但是如何获取联系人 ID...假设如果有两个号码以相同的名称保存,那么如何获取它特定联系人姓名的 ID?

您可以这样尝试: 导入框架

#import <Contacts/Contacts.h>

代码

- (void) getContacts {
    CNContactStore *store = [[CNContactStore alloc] init];
    [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted == YES) {
            //keys with fetching properties
            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) {
                    //store all the contacts as per your requirement
                    NSLog(@"Id %@",contact.identifier);//the contact id which you want
                    NSLog(@"Name %@",contact.givenName);
                }
            }
        }        
    }];
}