AddressBook、AddressBookUI、Contacts、ContactsUI 通讯录操作


iOS之前是使用 AddressBook Framework 访问通讯录,但从 iOS 9.0 开始被 Contacts Framework 替代,下面就看一下使用 AddressBook Framework 及 Contacts Framework 访问通讯录

一、访问通讯录及获取联系人

«« AddressBookFramework

/**
 访问通讯录
 */
- (void)requestAddressBookByAddressBookFramework {
    _addressBookRef = ABAddressBookCreateWithOptions(nil, nil);
    switch (ABAddressBookGetAuthorizationStatus()) {
        /** 用户拒绝或受限制直接返回 */
        case kABAuthorizationStatusDenied:
        case kABAuthorizationStatusRestricted:
        {
            [self authorizedAlert];
        }
            break;
        /** 未授权,请求授权 */
        case kABAuthorizationStatusNotDetermined:
        {
            ABAddressBookRequestAccessWithCompletion(_addressBookRef, ^(bool granted, CFErrorRef error) {
                if (!granted) {
                    [self authorizedAlert];
                }else {
                    [self getAddressBook];
                }
            });
        }
            break;
        /** 经授权,访问通讯录 */
        case kABAuthorizationStatusAuthorized:
        {
            [self getAddressBook];
        }
            break;
        default:
            break;
    }
    
}

/**
 读取联系人
 */
- (void)getAddressBook {
    NSArray *peoples = (__bridge NSArray *)(ABAddressBookCopyArrayOfAllPeople(_addressBookRef));
    _contactArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < peoples.count; i++) {
        ABRecordRef people = (__bridge ABRecordRef)(peoples[i]);
        NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(people, kABPersonLastNameProperty));
        NSString *secondName = (__bridge NSString *)(ABRecordCopyValue(people, kABPersonFirstNameProperty));
        ABMultiValueRef phoneNums = ABRecordCopyValue(people, kABPersonPhoneProperty);
        for (int i = 0; i < ABMultiValueGetCount(phoneNums); i++) {
            ContactModel *contactModel = [[ContactModel alloc] init];
            contactModel.name = [NSString stringWithFormat:@"%@%@", firstName ?: @"",secondName ?: @""];
            contactModel.phoneNumber = [((__bridge NSString *)(ABMultiValueCopyValueAtIndex(phoneNums, i))) stringByReplacingOccurrencesOfString:@"-" withString:@""];
            [_contactArray addObject:contactModel];
        }
    }
    NSLog(@"%@", [_contactArray yy_modelToJSONObject]);
}


«« ContactsFramework

/**
 请求访问通讯录
 */
- (void)requestAddressBookByContactsFramework {
    _contactStore = [[CNContactStore alloc] init];
    switch ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts]) {
        /** 未授权,请求授权 */
        case CNAuthorizationStatusNotDetermined:
        {
            [_contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
                if (!granted) {
                    [self authorizedAlert];
                }else {
                    [self getContacts];
                }
            }];
        }
            break;
        /** 用户拒绝或受限制直接返回 */
        case CNAuthorizationStatusDenied:
        case CNAuthorizationStatusRestricted:
        {
            [self authorizedAlert];
        }
            break;
        /** 经授权,访问通讯录 */
        case CNAuthorizationStatusAuthorized:
        {
            [self getContacts];
        }
            break;
            
        default:
            break;
    }
}

/**
 获取联系人
 */
- (void)getContacts {
    // 1. 创建联系人信息的请求对象
    NSArray *keys = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
    // 2. 根据请求Key, 创建请求对象
    CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:keys];
    _contactArray = [[NSMutableArray alloc] init];
    //3. 请求联系人数据
    [_contactStore enumerateContactsWithFetchRequest:request error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
        NSArray<CNLabeledValue<CNPhoneNumber*>*> *phoneNumbers = contact.phoneNumbers;
        for (CNLabeledValue *labeledValue in phoneNumbers) {
            ContactModel *contactModel = [[ContactModel alloc] init];
            contactModel.name = [NSString stringWithFormat:@"%@%@", contact.familyName ?: @"",contact.givenName ?: @""];
            CNPhoneNumber *phoneNumber = labeledValue.value;
            contactModel.phoneNumber = [[[phoneNumber.stringValue stringByReplacingOccurrencesOfString:@"-" withString:@""] stringByReplacingOccurrencesOfString:@"+86" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""];
            [_contactArray addObject:contactModel];
        }
    }];
    NSLog(@"%@", [_contactArray yy_modelToJSONObject]);
}

其中 ContactModel 是为了在自定义界面上展示联系人所创建的 model, authorizedAlert 为请求失败时所弹的提示,如下
- (void)authorizedAlert {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示"
                                                                             message:@"您当前未开启获取联系人权限,请前往设置开启权限"
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"我知道了"
                                                           style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction * _Nonnull action) {
                                                             [self.navigationController popViewControllerAnimated:YES];
                                                         }];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

二、对联系人增删改查

1、增加联系人

«« AddressBookFramework

«« ContactsFramework

/**
 添加联系人
 */
- (void)addContact {
    CNMutableContact * contact = [[CNMutableContact alloc]init];
    contact.imageData = UIImagePNGRepresentation([UIImage imageNamed:@"guojing"]);
    //设置名字
    contact.givenName = @"金诺";
    //设置姓氏
    contact.familyName = @"郭";
    contact.phoneNumbers = @[[CNLabeledValue labeledValueWithLabel:CNLabelPhoneNumberiPhone value:[CNPhoneNumber phoneNumberWithStringValue:@"12344312321"]]];
    //初始化方法
    CNSaveRequest * saveRequest = [[CNSaveRequest alloc]init];
    //    添加联系人(可以)
    [saveRequest addContact:contact toContainerWithIdentifier:nil];
    //    写入
    [_contactStore executeSaveRequest:saveRequest error:nil];
    [self getContacts];
}


2、更新联系人

«« AddressBookFramework

«« ContactsFramework

/**
 更新联系人
 */
- (void)updateContact {
    _contactStore = [[CNContactStore alloc] init];
    //检索条件,检索所有名字中有zhang的联系人
    NSPredicate * predicate = [CNContact predicateForContactsMatchingName:@"金诺"];
    //提取数据
    NSArray * contacts = [_contactStore unifiedContactsMatchingPredicate:predicate keysToFetch:@[CNContactGivenNameKey, CNContactFamilyNameKey] error:nil];
    
    for (CNContact *contact in contacts) {
        CNSaveRequest * saveRequest = [[CNSaveRequest alloc]init];
        CNMutableContact *mutableContact = [contact mutableCopy];
        mutableContact.familyName = @"慕容";
        [saveRequest updateContact:mutableContact];
        [_contactStore executeSaveRequest:saveRequest error:nil];
    }
}

3、删除联系人

«« AddressBookFramework

«« ContactsFramework

/**
 删除联系人
 */
- (void)deleteContact {
    _contactStore = [[CNContactStore alloc] init];
    //检索条件,检索所有名字中有zhang的联系人
    NSPredicate * predicate = [CNContact predicateForContactsMatchingName:@"金诺"];
    //提取数据
    NSArray * contacts = [_contactStore unifiedContactsMatchingPredicate:predicate keysToFetch:@[CNContactGivenNameKey, CNContactFamilyNameKey] error:nil];
    
    for (CNContact *contact in contacts) {
        CNSaveRequest * saveRequest = [[CNSaveRequest alloc]init];
        [saveRequest deleteContact:[contact mutableCopy]];
        [_contactStore executeSaveRequest:saveRequest error:nil];
    }
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值