取得手機資料庫的聯絡人

Framework -> AddressBook.framework
#import <AddressBook/AddressBook.h>

persons = [[NSMutableArray alloc] init];
ABAddressBookRef addressBook = ABAddressBookCreate();
ABRecordRef source = ABAddressBookCopyDefaultSource(addressBook);
NSArray *people = (NSArray *)ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, source, kABPersonSortByLastName);
for (id record in people)
{
    ABMultiValueRef numbers = ABRecordCopyValue((ABRecordRef)record, kABPersonPhoneProperty); 

    for (CFIndex i = 0; i < ABMultiValueGetCount(numbers); ++i) {
        CFStringRef label = ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(numbers, i));
        CFStringRef number = ABMultiValueCopyValueAtIndex(numbers, i);
        CFStringRef firstNameRef = ABRecordCopyValue((ABRecordRef)record, kABPersonFirstNameProperty);
        CFStringRef lastNameRef = ABRecordCopyValue((ABRecordRef)record, kABPersonLastNameProperty);
        CFDataRef imageDataRef = ABPersonCopyImageDataWithFormat((ABRecordRef)record, kABPersonImageFormatThumbnail);

        NSString *firstName = [NSString stringWithFormat:@"%@", firstNameRef];
        NSString *lastName = [NSString stringWithFormat:@"%@", lastNameRef];
        NSString *pLabel = [[NSString alloc] initWithFormat:@"%@", label];
        NSString *pNumber = [NSString stringWithFormat:@"%@", number];
        UIImage *image = [UIImage imageWithData:(NSData*)imageDataRef];

        NSDictionary *personDict = [NSDictionary dictionaryWithObjectsAndKeys:firstName, @"firstName", lastName, @"lastName", image, @"image", pNumber, @"phoneNumber", pLabel, @"label", nil];
        NSLog(@"In %@ - %@", pLabel, pNumber);

        [persons addObject:personDict];

        CFRelease(firstNameRef);
        CFRelease(lastNameRef);
        //CFRelease(imageDataRef);
        CFRelease(label);
        CFRelease(number);
    }
}
CFRelease(addressBook);
CFRelease(source);
[people release];

留言

熱門文章