详解iOS获取通讯录的4种方式

2020-01-18 16:42:26王振洲

Contact.framework

iOS10 需要在Info.plist配置NSContactsUsageDescription


<key>NSContactsUsageDescription</key>
<string>请求访问通讯录</string>  

应用启动时请求授权:

 


#import "AppDelegate.h"
#import <Contacts/Contacts.h>

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  // Override point for customization after application launch.

  [self requestAuthorizationForAddressBook];
  return YES;
}

- (void)requestAuthorizationForAddressBook {
  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);
      }
    }];
  }
}

@end

获取通讯录信息

 


#import "ViewController.h"
#import <Contacts/Contacts.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
  CNAuthorizationStatus authorizationStatus = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
  if (authorizationStatus == CNAuthorizationStatusAuthorized) {
    NSLog(@"没有授权...");
  }

  // 获取指定的字段,并不是要获取所有字段,需要指定具体的字段
  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);


    NSArray *phoneNumbers = contact.phoneNumbers;
    for (CNLabeledValue *labelValue in phoneNumbers) {
      NSString *label = labelValue.label;
      CNPhoneNumber *phoneNumber = labelValue.value;

      NSLog(@"label=%@, phone=%@", label, phoneNumber.stringValue);
    }

//    *stop = YES; // 停止循环,相当于break;
  }];

}
@end

运行效果:

iOS获取通讯录,iOS通讯录的获取