AddressBookFramework & Conta

2018-05-07  本文已影响18人  JimmyL

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

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

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];
}

二、对联系人增删改查

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];
}

更新联系人

/**
 更新联系人
 */
- (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];
    }
}

删除联系人

/**
 删除联系人
 */
- (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];
    }
}

AddressBookFramework

添加联系人

更新联系人

删除联系人

上一篇下一篇

猜你喜欢

热点阅读