項目中遇到一個需求,就是需要在入口的時候,獲取通訊錄的權限,並把所有的聯系人,以接口參數的形式傳到后台,通過網上查資料,歷時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字符串的方法,可以參考我寫的上一篇博客:過濾掉非法字符。
控制台輸出如下:

