2015-12-21 59 views
0

我能够使用电话号码搜索联系人姓名,但存在一些问题。如果地址簿中的号码具有国家代码和号码,并且如果我仅使用号码搜索,则返回emty值所以它不能以正确的方式搜索。这里是我所做的snipet代码。iPhone地址簿搜​​索使用号码

- (ABRecordRef)findRecord:(NSString *)phnNumber 
{ 
if (phnNumber == nil) 
    return nil; 



CFErrorRef error = nil; 
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error); 

if (!addressBook) { 
    NSLog(@"null"); 
} else if (error) { 
    NSLog(@"error %@",error); 
} 
// Requests access to address book data from the user 
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {}); 


CFArrayRef all = ABAddressBookCopyArrayOfAllPeople(addressBook); 


CFIndex n = ABAddressBookGetPersonCount(addressBook); 
ABRecordRef record; 

int count = 0; 

for(int i = 0 ; i < n ; i++) 
{ 
    ABRecordRef ref = CFArrayGetValueAtIndex(all, i); 

    ABMultiValueRef phones = ABRecordCopyValue(ref, kABPersonPhoneProperty); 

    for(CFIndex j = 0; j < ABMultiValueGetCount(phones); j++) 
    { 

     CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(phones, j); 

     NSString *newPhoneNumber = (__bridge NSString *)phoneNumberRef; 

     NSLog(@"%@",newPhoneNumber); 

     if([newPhoneNumber isEqualToString:phnNumber]) 
     { 
      record = ref; 

      i=(int)n; 
      count = 1; 
     } 
     CFRelease(phoneNumberRef); 
    } 

} 

if(count != 1) 
{ 
    ABRecordRef newPerson = ABPersonCreate(); 

    ABMutableMultiValueRef multiPhone = ABMultiValueCreateMutable(kABMultiStringPropertyType); 

    ABMultiValueAddValueAndLabel(multiPhone, (__bridge CFTypeRef)(phnNumber), kABHomeLabel, NULL); 

    ABRecordSetValue(newPerson, kABPersonPhoneProperty, multiPhone,nil); 
    CFRelease(multiPhone); 
    record = newPerson; 
} 


return record; 
} 

和我打电话这样说,这对名字:

ABRecordRef record = [self findRecord:@"Number_here"]; 

if(record){ 

    NSString *name =(__bridge NSString *)ABRecordCopyCompositeName(record); 

    lbCalleName.text=name; 
} 

我的问题是觉得─假设我有一个联系人和电话号码就像是8801723432323,我这个01723432323及以上搜索代码返回emty.Here 88是countrycode.Also我也需要相反的工作。假设我的给定号码在通讯录中有国家代码和国家代码。

回答

0

您可以使用[newPhoneNumber containsString:phnNumber]而不是[newPhoneNumber isEqualToString:phnNumber],但是您还应该更改逻辑,因为containsString方法可以匹配多个数字。

+0

我不明白我的观点。我告诉过如何看国家代码。假如我的给定号码在地址簿中有国家代码和国家代码,那么会发生什么?我需要这两个工作。 –

+0

试试看看这两个库: https://github.com/iziz/libPhoneNumber-iOS https://github.com/googlei18n/libphonenumber。 – lorenzoliveto

0

替换该行

if([newPhoneNumber isEqualToString:phnNumber]) 

if ([newPhoneNumber containsString:phnNumber]) 对iOS8上,后来和
NSRange range = [newPhoneNumber rangeOfString:phnNumber]; if (range.length != 0)较早的设备。 containsString:是在iOS8中引入的。