在iphone4s地址薄中获取联系人的实现

原问题来自于CSDN问答频道,更多解决方案见:http://ask.csdn.net/questions/1324

 

原问题描述:

+(NSMutableArray *)getLastName
{

   ABAddressBookRef addressBook = ABAddressBookCreate();
    NSMutableArray *lastNameArray = [[NSMutableArray alloc]init];
    ABRecordRef source = ABAddressBookCopyDefaultSource(addressBook);
    CFIndex numberOfContacts  = ABAddressBookGetPersonCount(addressBook);
    NSLog(@"%ld",numberOfContacts);
    CFArrayRef people = (__bridge CFArrayRef)((__bridge NSArray*)ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, source, kABPersonSortByLastName));
    NSArray * tempArray = [[NSArray alloc]init];
    tempArray = (__bridge  NSArray *)(people);
    if ([tempArray count]>0) {
    for (int personIndex = 0; personIndex < [tempArray count]-1; personIndex++) {
        ABRecordRef person = (__bridge ABRecordRef)([tempArray objectAtIndex:personIndex]);
        ABMultiValueRef lastName = ABRecordCopyValue(person, kABPersonLastNameProperty);
        NSString *lastNameString = (__bridge NSString *)lastName;
        if (lastName!=nil)
            [lastNameArray addObject:lastNameString];
          }
    }
    return lastNameArray;
}


上面的代码在xcode6.0iphone3s中就可以正常运行,但是在4s和5中就不运行了。

解决方案:

我觉得是IOS版本问题,在ios6.0中ABAddressBookCreate()不能用,只能在老版本中用,所以可以试试:

ABAddressBookRef addressBook;

if ([self isABAddressBookCreateWithOptionsAvailable])
{
    // iOS 6
    CFErrorRef error = nil;
    addressBook = ABAddressBookCreateWithOptions(NULL,&error);

    ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error)
                                             {
                                             });
    ABAddressBookRevert(addressBook);
}
else
{
    // iOS 4/5
    addressBook = ABAddressBookCreate();
}



-(BOOL)isABAddressBookCreateWithOptionsAvailable
{
    return &ABAddressBookCreateWithOptions != NULL;
}


 

你可能感兴趣的:(ios,ios,ios,移动开发,iPhone,iPhone,iPhone,iPhone,iPhone)