项目中遇到一个需求,就是需要在入口的时候,获取通讯录的权限,并把所有的联系人,以接口参数的形式传到后台,通过网上查资料,历时3个小时,终于完成,
话不多,直接上代码:
1,导入系统库
#import <Contacts/Contacts.h> #import <AddressBook/AddressBookDefines.h> #import <AddressBook/ABRecord.h> #import "AddressBook.h"
2,info.plist文件里面添加权限:
key: Privacy - Contacts Usage Description
value: App需要您的同意才能访问通讯录
3,添加获取权限的方法
- (void)requestAuthorizationForAddressBook { if ([[UIDevice currentDevice].systemVersion floatValue]>=9.0){ CNAuthorizationStatus authorizationStatus = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts]; if (authorizationStatus == CNAuthorizationStatusNotDetermined) { CNContactStore *contactStore = [[CNContactStore alloc] init]; [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) { if (granted) { } else { NSLog(@"授权失败, error=%@", error); } }]; } }else { [HTools showTextOnlyHud:@"请升级系统" delay:1.0]; } }
当然了,过低的系统,获取权限方法也不一样,可以在else方法里面自己做处理,这里我没有做处理!
4,用户点击允许后,获取通讯录所有的联系人信息:
- (void)getmyAddressbook { CNAuthorizationStatus authorizationStatus = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts]; if (authorizationStatus == CNAuthorizationStatusAuthorized) { NSLog(@"没有授权..."); } self.myDict = [[NSMutableDictionary alloc]init]; // 获取指定的字段,并不是要获取所有字段,需要指定具体的字段 NSArray *keysToFetch = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey]; CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch]; CNContactStore *contactStore = [[CNContactStore alloc] init]; [contactStore enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) { NSLog(@"-------------------------------------------------------"); NSString *givenName = contact.givenName; NSString *familyName = contact.familyName; NSLog(@"givenName=%@, familyName=%@", givenName, familyName); NSString *nameStr = [NSString stringWithFormat:@"%@%@",contact.familyName,contact.givenName]; NSArray *phoneNumbers = contact.phoneNumbers; for (CNLabeledValue *labelValue in phoneNumbers) { NSString *label = labelValue.label; phoneNumber = labelValue.value; NSLog(@"label=%@, phone=%@", label, phoneNumber.stringValue); } [_myDict setObject:phoneNumber.stringValue forKey:nameStr]; // *stop = YES; // 停止循环,相当于break; }]; NSLog(@"mydict is ==== %@",_myDict); }
放到字典里面,然后把字典转化成json字符串,去除非法字符,通过接口,传到后台就可以了!转json字符串的方法,可以参考我写的上一篇博客:过滤掉非法字符。
控制台输出如下: