iOS通讯录读写

首先引入addressBook.framework addressBookUI.framework框架

首先申请读写权限 
// Request authorization to Address Book
    ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
    
    if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
        ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
            // First time access has been granted, add the contact
        });
    }
    else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
        // The user has previously given access, add the contact
    }
    else {
        // The user has previously denied access
        // Send an alert telling user to change privacy setting in settings app
    }



添加通讯录

ABAddressBookRef iPhoneAddressBook = ABAddressBookCreate();
        ABRecordRef newPerson = ABPersonCreate();
        
        CFErrorRef error = NULL;
        
        ABRecordSetValue(newPerson, kABPersonFirstNameProperty, (__bridge CFTypeRef)(p.name), &error);
        
        //phone number
        ABMutableMultiValueRef multiPhone = ABMultiValueCreateMutable(kABMultiStringPropertyType);
        ABMultiValueAddValueAndLabel(multiPhone, (__bridge CFTypeRef)(p.number), kABPersonPhoneMainLabel, NULL);
        //        ABMultiValueAddValueAndLabel(multiPhone, @"1-123-456-7890", kABPersonPhoneMobileLabel, NULL);
        //        ABMultiValueAddValueAndLabel(multiPhone, @"1-987-654-3210", kABOtherLabel, NULL);
        ABRecordSetValue(newPerson, kABPersonPhoneProperty, multiPhone,&error);
        CFRelease(multiPhone);
        
        ABAddressBookAddRecord(iPhoneAddressBook, newPerson, &error);
        ABAddressBookSave(iPhoneAddressBook, &error);
        if (error != NULL)
        {
            NSLog(@"Danger Will Robinson! Danger!%@", error);
        }

删除通讯录


//打开电话本数据库
    ABAddressBookRef addressRef=ABAddressBookCreate();
    
    //返回所有联系人到一个数组中
    CFArrayRef personArray = ABAddressBookCopyArrayOfAllPeople(addressRef);
    
    //返回联系人数量
    CFIndex personCount = ABAddressBookGetPersonCount(addressRef);
    
    //循环读取每个联系人
    for (int i =0;i




你可能感兴趣的:(IOS开发)