2011-03-01 27 views
6

Belirli bir telefon numarası için iPhone adres defterini aramak ve sonra da kişi adını almak istiyorum. Şu anda tüm bağlantılardan geçiyorum ve çok değerli özellikleri ayıklayıp değere karşı karşılaştırıyorum. Bu çok zaman alıyor. Apple addressbook kılavuzunu okudum ve derler:Arama ABAddressbook iOS SDK

"aramaların diğer tür gerçekleştirmek işlevi ABAddressBookCopyArrayOfAllPeople kullanmak ve sonra NSArray yöntemi filteredArrayUsingPredicate kullanarak sonuçları filtrelemek :."

Bana bunun nasıl yapılacağına dair bir örnek verebilir misiniz?

Teşekkürler.

+0

bu yardımcı olabilir. Bu, diğer soru hakkındaki yanıtım, http: // stackoverflow.com/questions/4272164/nasıl yapılır arama-için-iphone-adres-kitap-için-belirli-telefon numarası/6953238 # 6953238 – ChangUZ

+0

Burada NSPredicate kullanarak yapmak için en etkili yolu: http: // hesh .am/2012/10/arama-bir-isim-kullanarak-telefon-numarası-in-abaddressbook/ –

cevap

9

Telefon numarası bulunan kişilerde arama yapmak isterseniz, size bir öneride bulunacağım.

1.Get tüm kişiler

NSArray *thePeoples = (NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook); 

2.Create iletişim dizisi (thePeoples) başka bir dizi (kayıt),

kayıt sayısı: [ record1, record2, .... recordN]

rekor: {name: "myContactName", phoneNumber: "1234567890"}

3. MutableArray (kayıtları) ile birlikte arama yapın. Bu, çözümünüzün basit bir örneğidir ve phoneNumber öğesinin bir multiValue alanı olduğunu unutmayın. Bu yüzden model sınıf değişkeninde telefon numarası olarak bir dizi içerecektir.

+1

Kişiler dizisinden başka bir dizi oluşturarak ne demek istiyorsunuz? – AlBeebe

+1

Bu nasıl çalışıyor? [<__ NSCFType 0x6e1f220> valueForUndefinedKey:]: bu sınıf, anahtar kaydı için kodlama uyumlu anahtar değer değil. –

2

Bunu Kullanın. bu benim kodum. Aramak için Diziyi yapın.

 NSLog(@"=====Make People Array with Numbers. Start."); 
     peopleWithNumber = [[NSMutableDictionary alloc] init]; 
     for (int i=0; i < [people count]; i++) { 
      NSInteger phoneCount = [self phoneCountAtIndex:i]; 
      if (phoneCount != 0) { 
       NSMutableArray *phoneNumbers = [[NSMutableArray alloc] init]; 
       for (int j=0 ; j < phoneCount ; j++) { 
        [phoneNumbers addObject:[self phoneNumberAtIndex:i phoneIndex:j]]; 
       } 
       [peopleWithNumber addEntriesFromDictionary: 
       [NSDictionary dictionaryWithObjectsAndKeys: 
        [NSArray arrayWithArray:phoneNumbers], [self fullNameAtIndex:i], nil]]; 
      } 
     } 
     NSLog(@"=====Make People Array with Numbers. End.\n"); 

Arama yöntemi. (peopleWithNumber) dizi (kullanıcı)

"NSArray * people = (NSArray *) ABAddressBookCopyArrayOfAllPeople (addressBook);

- (NSArray *)searchNamesByNumber:(NSString *)number { 

    NSString *predicateString = [NSString stringWithFormat:@"%@[SELF] contains '%@'",@"%@",number]; 
    NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:predicateString,peopleWithNumber,number]; 
    NSArray *names = [[peopleWithNumber allKeys] filteredArrayUsingPredicate:searchPredicate]; 

    return names; 
} 
2

Bir predicateWithFormat öğesini bir dizi ABRecordRef opak türüyle kullanamazsınız. Ama predicateWithBlock kullanabilirsiniz:

[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) { 
    ABRecordRef person=(__bridge ABRecordRef)evaluatedObject; 
    CFTypeRef theProperty = ABRecordCopyValue(person, kABPersonPhoneProperty); 
    NSArray *phones = (__bridge_transfer NSArray *) ABMultiValueCopyArrayOfAllValues(theProperty); 
    CFRelease(theProperty); 
    BOOL result=NO; 
    for (NSString *value in phones) { 
     if ([value rangeOfString:@"3"].location!=NSNotFound) { 
      result=YES; 
      break; 
     } 
    } 
    return result; 
}]; 
3

aşağıdaki yöntem verilen telefon numarasına sahip tüm kişileri içeren bir dizi döndürür. Bu yöntem, iOS7 çalıştıran iPhone 5'imde 250 kişiyi aramak için 0.02 saniye sürdü.

#import <AddressBook/AddressBook.h> 


-(NSArray *)contactsContainingPhoneNumber:(NSString *)phoneNumber { 
    /* 

    Returns an array of contacts that contain the phone number 

    */ 

    // Remove non numeric characters from the phone number 
    phoneNumber = [[phoneNumber componentsSeparatedByCharactersInSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]] componentsJoinedByString:@""]; 

    // Create a new address book object with data from the Address Book database 
    CFErrorRef error = nil; 
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error); 
    if (!addressBook) { 
     return [NSArray array]; 
    } else if (error) { 
     CFRelease(addressBook); 
     return [NSArray array]; 
    } 

    // Requests access to address book data from the user 
    ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {}); 

    // Build a predicate that searches for contacts that contain the phone number 
    NSPredicate *predicate = [NSPredicate predicateWithBlock: ^(id record, NSDictionary *bindings) { 
     ABMultiValueRef phoneNumbers = ABRecordCopyValue((__bridge ABRecordRef)record, kABPersonPhoneProperty); 
     BOOL result = NO; 
     for (CFIndex i = 0; i < ABMultiValueGetCount(phoneNumbers); i++) { 
      NSString *contactPhoneNumber = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(phoneNumbers, i); 
      contactPhoneNumber = [[contactPhoneNumber componentsSeparatedByCharactersInSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]] componentsJoinedByString:@""]; 
      if ([contactPhoneNumber rangeOfString:phoneNumber].location != NSNotFound) { 
       result = YES; 
       break; 
      } 
     } 
     CFRelease(phoneNumbers); 
     return result; 
    }]; 

    // Search the users contacts for contacts that contain the phone number 
    NSArray *allPeople = (NSArray *)CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook)); 
    NSArray *filteredContacts = [allPeople filteredArrayUsingPredicate:predicate]; 
    CFRelease(addressBook); 

    return filteredContacts; 
}