关于IOS获取本地通讯录信息(包含iOS9.0前后)

来源:互联网 发布:地球污染数据 编辑:程序博客网 时间:2024/06/11 19:41

在ios开发当中,获取用户本地的通讯录功能愈加频繁的出现,七两自己也在自己公司的项目当中遇到的获取本地的通讯录信息的功能(俗称“种子用户功能”,太可怕了)。对此七两总结了自己使用本地通讯录时的注意点,希望对大家有所帮助。

首先对于获取本地通讯录的信息,大苹果在ios9.0之后推出了另外的一个使用方式(controller),类似于之前searchcontroller与searchBar,对此七两在此分成两部分,ios9.0前与ios9.0后两部分进行总结。


一、iOS9.0前

先附上七两自己写得代码:
对于苹果对于通讯录的操作实现可以类比sqlite与sqlite3的管理实现方式,及我们在使用通讯录时需调用类似于sqlite3的管理对象,对此七两自己习惯将对通讯录的操作过程写成单例,具体如下:

.h文件
[objc] view plain copy
  1. #import <Foundation/Foundation.h>  
  2. #import <AddressBook/AddressBook.h>  
  3. #import <UIKit/UIKit.h>  
  4.   
  5. typedef void(^YFAddressBookBlock)(BOOL canRead, ABAuthorizationStatus authorStatus);  
  6.   
  7. @interface YFAddressBookManger : NSObject  
  8.   
  9. @property (nonatomic, assign) ABAddressBookRef addressBook;  
  10. //单例类方法  
  11. + (instancetype)shareManger;  
  12.   
  13. //设置传值  
  14. - (void)canReadAddressBookWithBlock:(YFAddressBookBlock)block;  
  15.   
  16. - (void)gotoSetting:(UIViewController *)vc;  
  17.   
  18. @end  

.m文件

[objc] view plain copy
  1. #import "YFAddressBookManger.h"  
  2.   
  3. @implementation YFAddressBookManger  
  4.   
  5. + (instancetype)shareManger{  
  6.     static YFAddressBookManger *manger = nil;  
  7.   
  8.     static dispatch_once_t onceToken;  
  9.     dispatch_once(&onceToken, ^{  
  10.         if (!manger) {  
  11.             manger = [[YFAddressBookManger alloc]init];  
  12.         }  
  13.     });  
  14.     return manger;  
  15. }  
  16.   
  17. - (id)init{  
  18.     self = [super init];  
  19.     if (self) {  
  20.         _addressBook = ABAddressBookCreateWithOptions(NULLNULL);  
  21.     }  
  22.       
  23.     return self;  
  24. }  
  25.   
  26. //获取读取权限  
  27. - (void)canReadAddressBookWithBlock:(YFAddressBookBlock)block{  
  28.     ABAuthorizationStatus authStatus = ABAddressBookGetAuthorizationStatus();  
  29.     if (authStatus == kABAuthorizationStatusNotDetermined) {  
  30.         ABAddressBookRequestAccessWithCompletion(_addressBook, ^(bool granted, CFErrorRef error) {  
  31.            dispatch_async(dispatch_get_main_queue(), ^{  
  32.                if (error) {  
  33.                    //拒绝访问  
  34.                    block(NO,kABAuthorizationStatusDenied);  
  35.                }else{  
  36.                    block(YES,0);  
  37.                }  
  38.            });  
  39.         });  
  40.     }else if (authStatus == kABAuthorizationStatusAuthorized){  
  41.         block(YES,0);  
  42.     }else{  
  43.         block(NO,authStatus);  
  44.     }  
  45. }  
  46.   
  47. //去设置页面  
  48. - (void)gotoSetting:(UIViewController *)vc{  
  49.     NSString *appName = [[NSBundle mainBundle].infoDictionary valueForKey:@"CFBundleDisplayName"];  
  50.     if (!appName) appName = [[NSBundle mainBundle].infoDictionary valueForKey:@"CFBundleName"];  
  51.     NSString *message = [NSString stringWithFormat:@"请在%@的\"设置-隐私-通讯录\"选项中,\r允许%@访问你的通讯录。",[UIDevice currentDevice].model,appName];  
  52.   
  53.     UIAlertController *alertVC = [[UIAlertController alloc]init];  
  54.     [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];  
  55.     UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {  
  56.         [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];  
  57.     }];  
  58.     UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {  
  59.           
  60.     }];  
  61.     [alertVC addAction:cancleAction];  
  62.     [alertVC addAction:sureAction];  
  63. }  
  64. @end  

后续引用通讯录中得数据至controller中的使用方式如下:
[objc] view plain copy
  1. #pragma mark - 获取本地的通讯录数据  
  2. - (void)getDataSource{  
  3.     if (_dataSource == nil) {  
  4.         _dataSource = [NSMutableArray new];  
  5.     }  
  6.     [[YFAddressBookManger shareManger]canReadAddressBookWithBlock:^(BOOL canRead, ABAuthorizationStatus authorStatus) {  
  7.         if (canRead) {  
  8.             ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULLNULL);  
  9.             CFArrayRef allLinkPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);  
  10.             CFIndex num = ABAddressBookGetPersonCount(addressBook);  
  11.             for (NSInteger i = 0; i < num; i++) {  
  12.                 ABRecordRef  people = CFArrayGetValueAtIndex(allLinkPeople, i);  
  13.                 ABMultiValueRef phones = ABRecordCopyValue(people, kABPersonPhoneProperty);  
  14.                   
  15.                 for (int k = 0; k<ABMultiValueGetCount(phones); k++)  
  16.                 {  
  17.                     //获取該Label下的电话值  
  18.                     NSString * personPhone = (__bridge NSString*)ABMultiValueCopyValueAtIndex(phones, k);  
  19.                       
  20.                     NSString *newP = [personPhone stringByReplacingOccurrencesOfString:@" " withString:@""];  
  21.                     newP = [newP stringByReplacingOccurrencesOfString:@"-" withString:@""];  
  22.                       
  23.                     // 去除+86  
  24.                     if ([newP containsString:@"+86"]) {  
  25.                         newP = [newP stringByReplacingOccurrencesOfString:@"+86" withString:@""];  
  26.                     }  
  27.                     // 去除+  
  28.                     if ([newP containsString:@"+"]) {  
  29.                         newP = [newP stringByReplacingOccurrencesOfString:@"+" withString:@""];  
  30.                     }  
  31.                     if (![_dataSource containsObject:newP]) {  
  32.                         [_dataSource addObject:newP];  
  33.                     }  
  34.                 }  
  35.                   
  36.             }  
  37.   
  38.         }else{  
  39.             [[YFAddressBookManger shareManger] gotoSetting:self];  
  40.         }  
  41.     }];  
  42. }  
如果需要其余的多余的单值属性需不同的字段,代码中的ABRecordCopyValue方法可以理解为C语言中得字典。即可根据不同的单值属性获取。

二、iOS9.0之后

苹果推荐ContactsUI使用,具体的使用方式如下:

[objc] view plain copy
  1. pragma mark - <CNContactPickerViewController代理方法>  
  2. /* 当选中一个联系人时,会执行该方法  
  3. @param picker 选择联系人的控制器  
  4. @param contact 选择的联系人 / 
  5. (void)contactPicker:(CNContactPickerViewController )picker didSelectContact:(CNContact )contact{ 
  6. // 1.获取联系人的姓名   NSString *firstName = contact.givenName; 
  7.   NSString *lastName = contact.familyName; 
  8.   NSLog(@"%@ %@", firstName, lastName); 
  9. // 2.获取联系人的电话号码   NSArray *phoneNumers = contact.phoneNumbers; 
  10.    for (CNLabeledValue *labelValue in phoneNumers) { 
  11.        CNPhoneNumber *phoneNumber = labelValue.value;  
  12.        NSString *phoneValue = phoneNumber.stringValue;  
  13.        NSString *phoneLabel = labelValue.label; 
  14.        NSLog(@"%@ %@", phoneValue, phoneLabel); 
  15.   } 
  16. } 
  17. /* 当选中某一个联系人的某一个属性时,会执行该方法  
  18. @param contactProperty 选中的联系人属性 
  19. */  
  20. (void)contactPicker:(CNContactPickerViewController )picker didSelectContactProperty:(CNContactProperty )contactProperty{}  


具体的细节使用如下:


[objc] view plain copy
  1. // 1.获取授权状态  
  2. CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];  
  3. // 2.如果不是已经授权,则直接返回  
  4. if (status != CNAuthorizationStatusAuthorized) return;  
  5.   
  6. // 3.获取联系人  
  7. // 3.1.创建联系人仓库  
  8. CNContactStore *store = [[CNContactStore alloc] init];  
  9.   
  10. // 3.2.创建联系人的请求对象  
  11. // keys决定这次要获取哪些信息,比如姓名/电话  
  12. NSArray *fetchKeys = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];  
  13. CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:fetchKeys];  
  14.   
  15. // 3.3.请求联系人  
  16. NSError *error = nil;  
  17. [store enumerateContactsWithFetchRequest:request error:&error usingBlock:^(CNContact * _Nonnull contact, BOOLBOOL * _Nonnull stop) {  
  18.     // stop是决定是否要停止  
  19.     // 1.获取姓名  
  20.     NSString *firstname = contact.givenName;  
  21.     NSString *lastname = contact.familyName;  
  22.     NSLog(@"%@ %@", firstname, lastname);  
  23.   
  24.     // 2.获取电话号码  
  25.     NSArray *phones = contact.phoneNumbers;  
  26.   
  27.     // 3.遍历电话号码  
  28.     for (CNLabeledValue *labelValue in phones) {  
  29.         CNPhoneNumber *phoneNumber = labelValue.value;  
  30.         NSLog(@"%@ %@", phoneNumber.stringValue, labelValue.label);  
  31.     }  
  32. }];  
原创粉丝点击