3

I have a text field with a contact name and I want to get the phone number for that:

ABAddressBookRef adressBook = ABAddressBookCreate();

NSArray *people = (NSArray *)ABAddressBookCopyPeopleWithName(adressBook,
                               CFStringCreateCopy(kCFAllocatorDefault, 
                                                 (CFStringRef)recipient));

if((people != nil) && ([people count] == 1)){
    ABMultiValueRef person = (ABMultiValueRef)[people objectAtIndex:0];
    NSString *phone = (NSString *)ABRecordCopyValue(person, 
                                                      kABPersonPhoneProperty) ;
    NSLog(@"%@", phone);
}

I want the phone number as string but this gives me a lot more:

ABMultiValueRef 0x339470 with 1 value(s)
    0: _$!<Mobile>!$_ (0x338c50) - 0177 1647788 (0x339450)

How to I get just the number as string?

DarkLeafyGreen
  • 69,338
  • 131
  • 383
  • 601

4 Answers4

11
NSMutableArray *phoneNumbers = [[[NSMutableArray alloc] init] autorelease];
ABMultiValueRef multiPhones = ABRecordCopyValue(person,kABPersonPhoneProperty);
for(CFIndex i=0;i<ABMultiValueGetCount(multiPhones);++i) {
    CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, i);
    NSString *phoneNumber = (NSString *) phoneNumberRef;

    [phoneNumbers addObject:phoneNumber];
}
unexpectedvalue
  • 6,079
  • 3
  • 38
  • 62
  • thanks that helped, but why I need to loop over it since I have just one contact? you example gives me ( 1222... ) with that round brackets, how to get the string without the brackets? – DarkLeafyGreen Apr 13 '11 at 18:53
  • One contact can have multiple numbers, the numbers will be stored in the array 'phoneNumbers'. To get the first: [phoneNumbers objectAtIndex:0] – unexpectedvalue Apr 14 '11 at 09:23
2

kABPersonPhoneProperty is a multi-value property, but you're treating it as a string. You should get the individual numbers and print them separately.

Caleb
  • 124,013
  • 19
  • 183
  • 272
1

For those searching for phone extraction. You can extract the phone numbers from a text and then replace it with @"", for example:

NSString *userBody = @"This is a text with 30612312232 my phone";
if (userBody != nil) {
    NSError *error = NULL;
    NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber error:&error];
    NSArray *matches = [detector matchesInString:userBody options:0 range:NSMakeRange(0, [userBody length])];
    if (matches != nil) {
        for (NSTextCheckingResult *match in matches) {
            if ([match resultType] == NSTextCheckingTypePhoneNumber) {
                DbgLog(@"Found phone number %@", [match phoneNumber]);
            }
        }
    }
}

`

Rafael Sanches
  • 1,823
  • 21
  • 28
1
CFStringRef phoneRef = ABRecordCopyValue(person, kABPersonPhoneProperty) ;
NSString *phoneNumber = (NSString *) phoneRef;
Michaël
  • 6,676
  • 3
  • 36
  • 55