2013-04-28 66 views
3

我试图在iOS中以编程方式替换特定联系人的特定电话号码,并取得联系人表单地址簿。如何以编程方式从通讯簿中编辑电话号码值ios

我不知道为什么我无法保存新的电话号码并刷新地址簿以显示更改。

我这样做:

+(BOOL) changeContactPhoneNumber:(NSString *) phoneSought 
       forThis:(NSString *) newPhoneNumber{ 

ABAddressBookRef addressBook = ABAddressBookCreate(); 
ABRecordRef contactSelected; 
CFStringRef mobileLabelNumber; 
CFErrorRef error = nil; 

// Do whatever you want here. 
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook); 
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook); 

for (int i = 0; i < nPeople; i++) 
{ 

    ABRecordRef ref = CFArrayGetValueAtIndex(allPeople, i); 

    ABMultiValueRef phones = (ABMultiValueRef)ABRecordCopyValue(ref, kABPersonPhoneProperty); 
    NSString* [email protected]""; 


    if (ABMultiValueGetCount(phones) > 0) { 
     for (int i=0; i < ABMultiValueGetCount(phones); i++) { 
      [mobilePhoneNumber release]; 
      mobilePhoneNumber = (NSString*)ABMultiValueCopyValueAtIndex(phones, i); 

      if([mobilePhoneNumber isEqualToString:phoneSought]){ 
       contactSelected = ref; 
       mobileLabelNumber = ABMultiValueCopyLabelAtIndex(phones, i); 
      } 
     } 
    } 
} 

ABMutableMultiValueRef phoneNumberMultiValue = ABMultiValueCreateMutable(kABPersonPhoneProperty); 
bool didAddPhone = ABMultiValueAddValueAndLabel(phoneNumberMultiValue ,(__bridge CFTypeRef)newPhoneNumber,mobileLabelNumber, NULL); 


if(didAddPhone){ 
    ABRecordSetValue(ABAddressBookGetPersonWithRecordID(addressBook, contactSelected), 
        kABPersonPhoneProperty, 
        phoneNumberMultiValue, 
        nil); 

    bool bSuccess = ABAddressBookSave(addressBook, &error); 
    if (!bSuccess) { 
     NSLog(@"Could not save to address book: %@", error); 
    } else { 
     return YES; 
    } 

} else { 
    NSLog(@"Error editing phone number: %@", error); 
    error = nil; 
} 

return NO; 
} 
+0

我可以知道你使用的是哪个IOS版本吗? – 2013-04-28 03:20:56

+0

现在我正在使用从iOs 4.3到最后一个版本(6.1.3)...我有另一种方法之前,我要求的权限,如果用户有iOs 6 – bubudrc 2013-04-28 03:33:29

+0

你没有提到实际发生了什么码。它有多远?怎么了? – rmaddy 2013-04-28 05:30:16

回答

3

你应该调试你的代码,并试图找出你是否提供给该方法的电话号码的格式符合。

例如,当我登录我的联系人列表中的电话号码这些结果

Number...555-478-7672 
Number...(408) 439-5270 
Number...(408) 555-3514 
Number...888-555-5512 
Number...888-555-1212 
Number...555-522-8243 
Number...(555) 766-4823 
Number...(707) 555-1854 
Number...555-610-6679 

,我是比较反对未格式化的数字字符串,这些数字。

其次

ABRecordSetValue(ABAddressBookGetPersonWithRecordID(addressBook, contactSelected), 
       kABPersonPhoneProperty, 
       phoneNumberMultiValue, 
       nil); 

且实际的声明是

ABRecordSetValue(ABRecordRef record, ABPropertyID property, CFTypeRef value, CFErrorRef* error); 

虽然ABAddressBookGetPersonWithRecordID返回ABRecordRef但是你已经有ABRecordRef contactSelected;所以在我看来,你应该使用

ABRecordSetValue(contactSelected,kABPersonPhoneProperty,phoneNumberMultiValue,nil); 

请指正如果我错了或误解了你的代码!

相关问题