检索联系人-2

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event {

//1.创建系统通讯录CNContactStore:存储者系统通讯录中的和联系人相关的所有数据

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

//2.检索获取系统通讯录的请求者CNContactFetchRequest

//2.1要先准备要获取的属性对应的key

NSArray * keys = @[CNContactFamilyNameKey,CNContactGivenNameKey,CNContactPhoneNumbersKey];

//2.2创建一个请求对象(CNContactFetchRequest检索请求的类)

CNContactFetchRequest * request = [[CNContactFetchRequest alloc] initWithKeysToFetch:keys];

//2.3遍历所有的联系人检索出想要拿到的数据enumerateContactsWithFetchRequest contact联系人对象

[store enumerateContactsWithFetchRequest:request error:nil usingBlock:^(CNContact*_Nonnullcontact,BOOL*_Nonnullstop) {

//获取联系人的姓名

NSString * lastName = contact.familyName;

NSString * firstName = contact.givenName;

//电话号码

CNPhoneNumber * number =  contact.phoneNumbers[0].value;

NSString * phoneStr = number.stringValue;

NSLog(@"%@.%@----%@",firstName,lastName,phoneStr);

}];

//1.创建系统通讯录

CNContactStore * store = [[CNContactStorealloc]init];

//检索联系人

//2.1检索条件unifiedContactsMatchingPredicate:(nonnull NSPredicate *)

//predicate通过匹配姓名中有相关字段字母的数据可以为空,但是会有⚠️

//2.2检索数据keysToFetch:(nonnull NSArray> *)   keys

NSPredicate* predicate = [CNContactpredicateForContactsMatchingName:@"App"];

//2.3想要获取的数据对应的key

NSArray* keys = @[CNContactFamilyNameKey,CNContactGivenNameKey,CNContactPhoneNumbersKey];

//2.4用数组进行接收

NSArray* contactArray =[store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:nil];

//firstObject  lastObject

CNContact * contact = contactArray.firstObject;

NSString * firstName =  contact.givenName;

NSString * lastName =  contact.familyName;

//索引0.1都不蹦联系人有两个电话号码

CNPhoneNumber * number = contact.phoneNumbers[0].value;

NSString * phoneStr = number.stringValue;

NSLog(@"%@.%@ --%@",firstName,lastName,phoneStr);

}

你可能感兴趣的:(检索联系人-2)