DarkLeafyGreen
DarkLeafyGreen

Reputation: 70466

How to get phone number from address book as string?

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?

Upvotes: 3

Views: 5311

Answers (4)

Rafael Sanches
Rafael Sanches

Reputation: 1823

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]);
            }
        }
    }
}

`

Upvotes: 1

Caleb
Caleb

Reputation: 125037

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

Upvotes: 2

unexpectedvalue
unexpectedvalue

Reputation: 6139

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];
}

Upvotes: 11

Micha&#235;l
Micha&#235;l

Reputation: 6734

CFStringRef phoneRef = ABRecordCopyValue(person, kABPersonPhoneProperty) ;
NSString *phoneNumber = (NSString *) phoneRef;

Upvotes: 1

Related Questions