Objective-C use Contacts.framework 聯絡人資訊

GorgoasTW
Oct 27, 2020

Step1

Add Framework

#import <Contacts/Contacts.h>
#import <ContactsUI/ContactsUI.h>

Step2

Add Privacy

Privacy - Contacts Usage Description

Step3

Check Authorization Status

CNContactStore *contactStore = [[CNContactStore alloc] init];

if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusNotDetermined) {
[contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!error){
if (granted) {
NSLog(@"authorized");
[self fetchContactWithContactStore:contactStore];
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"contacts:%@", contacts);
});
} else {
NSLog(@"denied");
}
} else {
NSLog(@"error!");
}
}];
} else {
[self fetchContactWithContactStore:contactStore];
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"contacts:%@", contacts);
});
}

Step4

code

- (NSMutableArray *)fetchContactWithContactStore:(CNContactStore *)contactStore {
if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusAuthorized) {
NSError *error = nil;
NSArray <id<CNKeyDescriptor>> *keysToFetch = @[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey];
NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:contactStore.defaultContainerIdentifier];
NSArray<CNContact*> *arr = [contactStore unifiedContactsMatchingPredicate:predicate keysToFetch:keysToFetch error:&error];

if (!error) {
NSMutableArray *contacts = [NSMutableArray array];
for (int i = 0; i < arr.count; i++) {
CNContact *contact = arr[i];
NSString *givenName = contact.givenName;
NSString *familyName = contact.familyName;
NSString *phoneNumber = ((CNPhoneNumber *)(contact.phoneNumbers.lastObject.value)).stringValue;

[contacts addObject:@{@"name":[givenName stringByAppendingString:familyName], @"phoneNumber":phoneNumber}];
}
return contacts;
} else {
return nil;
}
} else {
NSLog(@"denied");
return nil;
}
}

--

--

GorgoasTW
0 Followers

iOS Developer/.NET Developer/Father