網上找了一段代碼,還專門升級了ios設備和xcode,測試結果是可行得
+ (NSArray *) ABContacts {
float version = [UIDevice currentDevice].systemVersion.floatValue;
NSMutableArray *ret = nil;
if(version >= 6.0)
{
NSLog(@"get contacts by >= 6.0 api");
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(nil, nil);
//等待同意後向下執行
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error)
{
dispatch_semaphore_signal(sema);
});
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
dispatch_release(sema);
CFArrayRef ppRef = ABAddressBookCopyArrayOfAllPeople(addressBook);
ret = [NSMutableArray array];
for (id record in (NSArray *)ppRef) {
@try {
Contact *contact = [Contact contactWithABRecordRef:record];
//NSLog(@"contact name = %@",contact.compositeName);
[contact initForSearchWithRecord:record];
//NSLog(@"init for search");
[ret addObject:contact];
}
@catch (NSException *exception) {
}
@finally {
}
}
NSLog(@"ab size = %d",[ret count]);
CFRelease(ppRef);
CFRelease(addressBook);
}else{
NSLog(@"get contacts by < 6.0 api");
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef ppRef = ABAddressBookCopyArrayOfAllPeople(addressBook);
ret = [NSMutableArray array];
for (id record in (NSArray *)ppRef) {
@try {
Contact *contact = [Contact contactWithABRecordRef:record];
//NSLog(@"contact name = %@",contact.compositeName);
[contact initForSearchWithRecord:record];
//NSLog(@"init for search");
[ret addObject:contact];
}
@catch (NSException *exception) {
}
@finally {
}
}
CFRelease(ppRef);
CFRelease(addressBook);
}
return ret;
}