iOS9之后推荐使用CNContactViewController代替ABNewPersonViewController

否则有可能出现如下闪退:

*** Terminating app due to uncaught exception 'CNPropertyNotFetchedException', reason: 'A property was not requested when contact was fetched.'

所以区分了系统调用不同的实现方法

//创建新的联系人
- (void)creatNewRecord {
    
    if([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) {
        CNMutableContact *contact = [[CNMutableContact alloc]init];
        contact.nickname = @"zhongshan";
        
        //电话
        CNLabeledValue *phoneNumber = [CNLabeledValue labeledValueWithLabel:CNLabelPhoneNumberMobile value:[CNPhoneNumber phoneNumberWithStringValue:@"18322222222"]];
        contact.phoneNumbers = @[phoneNumber];
        
        //5.跳转到新建联系人页面
        CNContactViewController *mVC = [CNContactViewController viewControllerForNewContact:contact];
        mVC.delegate = self;
        [self.navigationController pushViewController:mVC animated:YES];
        return;
    }
    
    NSMutableDictionary *recordDict = [[NSMutableDictionary alloc]init];
    [recordDict setObject:@"zhongshan" forKey:@"name"];
    [recordDict setObject:@"18322222222" forKey:@"phone"];

    CFErrorRef error = NULL;
    //创建一个通讯录操作对象
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
    //创建一条新的联系人纪录
    ABRecordRef newRecord = ABPersonCreate();
    //为新联系人记录添加属性值
    ABRecordSetValue(newRecord, kABPersonFirstNameProperty, (__bridge CFTypeRef)[recordDict objectForKey:@"name"], &error);

    //创建一个多值属性(电话)
    ABMutableMultiValueRef multi = ABMultiValueCreateMutable(kABMultiStringPropertyType);
    ABMultiValueAddValueAndLabel(multi, (__bridge CFTypeRef)[recordDict objectForKey:@"phone"], kABPersonPhoneMobileLabel, NULL);
    ABRecordSetValue(newRecord, kABPersonPhoneProperty, multi, &error);

    //添加记录到通讯录操作对象
    ABAddressBookAddRecord(addressBook, newRecord, &error);

    //保存通讯录操作对象
    ABAddressBookSave(addressBook, &error);
    
    ABNewPersonViewController *picker = [[ABNewPersonViewController alloc] init];
    picker.newPersonViewDelegate = self;
    picker.addressBook = addressBook;
    picker.displayedPerson = newRecord;
    [self.navigationController pushViewController:picker animated:YES];
    
    CFRelease(multi);
    CFRelease(newRecord);
    CFRelease(addressBook);

}

#pragma mark - ABNewPersonViewControllerDelegate
- (void)newPersonViewController:(ABNewPersonViewController *)newPersonView didCompleteWithNewPerson:(ABRecordRef)person {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - CNContactViewControllerDelegate
- (void)contactViewController:(CNContactViewController *)viewController didCompleteWithContact:(CNContact *)contact {
    [self.navigationController popViewControllerAnimated:YES];
}

 

posted on 2017-06-22 10:51  fatal-奚山遇白  阅读(1150)  评论(0编辑  收藏  举报