0

I'm trying to get the Twitter username from a contact in the address book but I'm not able to do it

I'm using this code that I found "googling":

- (NSString*)getTwitterUsernameFromRecord:(ABRecordRef)record {
    NSString * twitterUsername = nil;

    ABMultiValueRef socials = ABRecordCopyValue(record, kABPersonSocialProfileProperty);

    if (!socials) {
        return nil;
    }

    CFIndex socialsCount = ABMultiValueGetCount(socials);

    for (int k=0 ; k<socialsCount ; k++) {
        CFDictionaryRef socialValue = ABMultiValueCopyValueAtIndex(socials, k);
        if(CFStringCompare( CFDictionaryGetValue(socialValue, kABPersonSocialProfileServiceKey), kABPersonSocialProfileServiceTwitter, 0)==kCFCompareEqualTo) {
            twitterUsername = (NSString*) CFDictionaryGetValue(socialValue, kABPersonSocialProfileUsernameKey);
        }
        CFRelease(socialValue);

        if(twitterUsername)
            break;
    }
    CFRelease(socials);

    return twitterUsername;
}

I've put the if to validate the "socials" array is nil because I was getting exception when trying to get "socials" array count.

I've tried this code in the simulator and in a real device with contacts which twitter info is filled but the "socials" array I get is always nil. I'm getting the wrong property from the record? Any help?

Thank you in advance

rai212
  • 711
  • 1
  • 6
  • 20

1 Answers1

1

your function works for me almost as-is, aside from needing to bridge cast the twitter username (which is just an ARC thing). how are you accessing the address book?

when i use this code to call your function:

ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);

CFIndex contactCount = ABAddressBookGetPersonCount(addressBook);

for( int i = 0; i<contactCount; i++ )
{
    ABRecordRef ref = CFArrayGetValueAtIndex(people, i);
    NSString *twitterHandle = [self getTwitterUsernameFromRecord:ref];
    if (twitterHandle) {
        NSLog(@"record %d has twitter name %@", i, twitterHandle);
    }
}

i get this console output:

2012-06-26 12:09:40.864 AddressBookTest[2246:707] record 57 has twitter name alexshepard
Alex Shepard
  • 333
  • 2
  • 10
  • Ok, It's embarrassing... :D I was so obsessed with the method "getTwitterUsernameFromRecord" that I didn't pay attention to the previous code. I was doing the same as you to get the contacs but just after ABAddressBookGetPersonCount(addressBook); I was releasing addressBook (with CFRelease(addressBook)) and this was causing the error. Thank you very much for your help – rai212 Jun 26 '12 at 20:07