美文网首页
iOS9之后访问通讯录-Contacts和ContactsUI

iOS9之后访问通讯录-Contacts和ContactsUI

作者: 兔兔小八哥 | 来源:发表于2016-07-14 10:54 被阅读386次

    1.Contacts的四种用户访问状态

    代码:

    CNAuthorizationStatus status =

    [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];

    switch (status) {

    case CNAuthorizationStatusNotDetermined:

    NSLog(@"首次访问这个软件没有获得用户许可");

    break;

    case CNAuthorizationStatusRestricted:

    NSLog(@"被家长限制了");

    break;

    case CNAuthorizationStatusDenied:

    NSLog(@"用户拒绝软件访问通讯录");

    break;

    case CNAuthorizationStatusAuthorized:

    NSLog(@"用户允许软件访问通讯录");

    break;

    default:

    break;

    }

    图1.1

    2.申请授权-访问用户的通讯录

    代码:

    - (void)checkAddressBookAuthorization:(void (^)(bool isAuthorized))block{

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

    CNAuthorizationStatus authStatus = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];;

    if (authStatus != CNAuthorizationStatusAuthorized){

    [addressBook requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {

    dispatch_async(dispatch_get_main_queue(), ^{

    if (error){

    NSLog(@"Error: %@",error);

    }else if (!granted){

    block(NO);

    }else{

    block(YES);

    }

    });

    }];

    }else{

    block(YES);

    }

    }

    图2.1

    3.授权成功以后遍历通讯录

    [self checkAddressBookAuthorization:^(bool isAuthorized) {

    if (isAuthorized) {

    // 1.创建通信录对象

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

    // 2.创建获取通信录的请求对象

    // 2.1.拿到所有打算获取的属性对应的key

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

    // 2.2.创建CNContactFetchRequest对象

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

    // 3.遍历所有的联系人

    [contactStore enumerateContactsWithFetchRequest:request error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {

    // 1.获取联系人的姓名

    NSString *lastname = contact.familyName;

    NSString *firstname = contact.givenName;

    NSLog(@"%@ %@", lastname, firstname);

    // 2.获取联系人的电话号码

    NSArray *phoneNums = contact.phoneNumbers;

    for (CNLabeledValue *labeledValue in phoneNums) {

    // 2.1.获取电话号码的KEY

    NSString *phoneLabel = labeledValue.label;

    // 2.2.获取电话号码

    CNPhoneNumber *phoneNumer = labeledValue.value;

    NSString *phoneValue = phoneNumer.stringValue;

    NSLog(@"%@ %@", phoneLabel, phoneValue);

    }

    }];

    }

    }];

    图3.1

    4.ContactsUI的简单使用

    图4.1创建实例跳转到联系人列表 图4.2引入对象,遵循协议 图4.3实现代理方法

    相关文章

      网友评论

          本文标题:iOS9之后访问通讯录-Contacts和ContactsUI

          本文链接:https://www.haomeiwen.com/subject/kuyejttx.html