ios6新增加了隐私授权功能,访问通讯录也需要授权。
ios6的sdk新增加了一个函数ABAddressBookRequestAccessWithCompletion
说明如下:
注意这个函数是在ios6.0和以上版本才有效。其他版本这个函数是个空值。还有如果代码里面使用了这个函数,那么xcode工程里面需要设置ios6 sdk,不然编译会出错。
下面的代码在xcode 4.5和iOS 6 sdk里面通过,ios4.3和以上版本运行正常,其中ios 6上面会弹出一个对话框,让用户选择是否给当前的app授权使用通讯录。(只会弹一次,即使重装app也不会弹第二次了,当然可以在设置里面去修改是否授权)
+ (NSString*) GetAllContacts
{
NSString* contacts = @"";
ABAddressBookRef addressBook = ABAddressBookCreate();
if (addressBook == nil) {
return nil;
}
__block BOOL accessGranted = NO;
if (ABAddressBookRequestAccessWithCompletion != NULL) { // we're on iOS 6
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
accessGranted = granted;
dispatch_semaphore_signal(sema);
});
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
dispatch_release(sema);
}
else { // we're on iOS 5 or older
accessGranted = YES;
}
if (!accessGranted) {
return nil;
}
CFArrayRef results = ABAddressBookCopyArrayOfAllPeople(addressBook);
for(int i = 0; i < CFArrayGetCount(results); i++)
{
ABRecordRef person = CFArrayGetValueAtIndex(results, i);
NSString* ContactName = @"";
//读取firstname
NSString *personName = (NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);
if(personName != nil)
ContactName = [ContactName stringByAppendingFormat:@"%@",personName];
//读取middlename
NSString *middlename = (NSString*)ABRecordCopyValue(person, kABPersonMiddleNameProperty);
if(middlename != nil)
ContactName = [ContactName stringByAppendingFormat:@"%@",middlename];
//读取lastname
NSString *lastname = (NSString*)ABRecordCopyValue(person, kABPersonLastNameProperty);
if(lastname != nil)
ContactName = [ContactName stringByAppendingFormat:@"%@",lastname];
NSString* separator = @"#41#";//随便搞个分隔符
NSString* numbers = @"";
//读取电话多值
ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
for (int k = 0; k<ABMultiValueGetCount(phone) ; k++)
{
NSString * personPhone = (NSString*)ABMultiValueCopyValueAtIndex(phone, k);
if (personPhone) {
numbers = [numbers stringByAppendingFormat:@"%@%@", personPhone, separator];
}
}
if (numbers.length > 0) {
NSString* contact = [NSString stringWithFormat:@"<Contact><ContactName>%@</ContactName><Phones>%@</Phones><emailaddress></emailaddress></Contact>", ContactName, numbers];
contacts = [contacts stringByAppendingFormat:@"%@", contact];
}
}
CFRelease(results);
CFRelease(addressBook);
if (contacts.length > 0) {
return [NSString stringWithFormat:@"<AddressBook>%@</AddressBook>", contacts];
}
else {
return @"";
}
}