先获取权限 不然会崩溃
在包头文件
Contacts/Contacts.h 他是基于这个框架
好了就不多说了 直接上代码
if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusNotDetermined) {
CNContactStore *store = [[CNContactStore alloc] init];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted) {
NSLog(@”授权成功”);
// 2. 获取联系人仓库
CNContactStore * store = [[CNContactStore alloc] init];
// 3. 创建联系人信息的请求对象
NSArray * keys = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
// 4. 根据请求Key, 创建请求对象
CNContactFetchRequest * request = [[CNContactFetchRequest alloc] initWithKeysToFetch:keys];
// 5. 发送请求
[store enumerateContactsWithFetchRequest:request error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
// 6.1 获取姓名
NSString * givenName = contact.givenName;
NSString * familyName = contact.familyName;
NSLog(@"%@--%@", givenName, familyName);
// 6.2 获取电话
NSArray * phoneArray = contact.phoneNumbers;
for (CNLabeledValue * labelValue in phoneArray) {
CNPhoneNumber * number = labelValue.value;
NSLog(@"%@--%@", number.stringValue, labelValue.label);
}
}];
}
}];
}