1. 程式人生 > >iOS編輯系統通訊錄

iOS編輯系統通訊錄

有時會用到需要修改系統通訊錄,百度了一下可以用CNContactStore進行操作,不過好像是有版本限制

//查詢系統通訊錄裡的某個聯絡人
CNContactStore * stroe = [[CNContactStore alloc]init];
//檢索條件,檢索所有名字中有‘’拉拉“的聯絡人
NSPredicate * predicate = [CNContact predicateForContactsMatchingName:@”拉拉“];

//得到的聯絡人 (說明:keysToFetch:想要修改什麼屬性就必須設定什麼屬性,否則程式崩潰)
NSArray * contacts = [stroe unifiedContactsMatchingPredicate:predicate keysToFetch:@[CNContactGivenNameKey,CNContactFamilyNameKey,CNContactOrganizationNameKey,CNContactThumbnailImageDataKey,CNContactImageDataKey,CNContactNoteKey,CNContactPhoneNumbersKey] error:nil];

CNMutableContact *contact2 = [contacts[0] mutableCopy];
contact2.imageData = UIImagePNGRepresentation(_headImage);//修改頭像
contact2.givenName = _nameField.text;//修改名字
contact2.familyName = _nameField.text;//修改姓
contact2.note = _remarkFiled.text;//修改備註
//處理要修改的號碼
NSMutableArray *numbers = [NSMutableArray arrayWithCapacity:10];
//修改寫入多個號碼
for (PrefileViewModel *model in _dataMarr) {
if (model.value.length !=0) {
CNLabeledValue *phoneNumber = [CNLabeledValue labeledValueWithLabel:CNLabelPhoneNumberMobile value:[CNPhoneNumber phoneNumberWithStringValue:model.value]];
[numbers addObject:phoneNumber];
}
}
contact2.phoneNumbers = numbers;//修改號碼
CNSaveRequest * saveRequest = [[CNSaveRequest alloc]init];
[saveRequest updateContact:contact2];
[stroe executeSaveRequest:saveRequest error:nil];

//新建
CNContactStore * stroe = [[CNContactStore alloc]init];
CNMutableContact *newContact = [[CNMutableContact alloc]init]; newContact.givenName = _nameField.text;
newContact.note = _remarkFiled.text;
NSMutableArray *numbers = [NSMutableArray arrayWithCapacity:10];
for (PrefileViewModel *model in _dataMarr) {
if (model.value.length !=0) {
CNLabeledValue *phoneNumber = [CNLabeledValue labeledValueWithLabel:CNLabelPhoneNumberMobile value:[CNPhoneNumber phoneNumberWithStringValue:model.value]];
[numbers addObject:phoneNumber];
}
}
newContact.phoneNumbers = numbers;
newContact.imageData = UIImagePNGRepresentation(_headImage);
CNSaveRequest * saveRequest = [[CNSaveRequest alloc]init];
[saveRequest addContact:newContact toContainerWithIdentifier:nil];
[stroe executeSaveRequest:saveRequest error:nil];

//獲取通訊錄聯絡人的頭像 (contact2同上)
if ([contact2 isKeyAvailable:CNContactThumbnailImageDataKey])
{

        NSData * thumImageData = contact2.thumbnailImageData;

        UIImage *image= [UIImage imageWithData:thumImageData];

        if (thumImageData !=NULL) {

            _headerImageView.image = image;
        }



    }

//獲取手機號碼
NSArray *numbers = contact2.phoneNumbers;
//獲取備註
if ([contact2 isKeyAvailable:CNContactNoteKey])
{
NSString * noteString= contact2.note;

        if (noteString.length !=0) {

            _remarkFiled.text = noteString;
        }

    }