嗨,我正在开发一个应用程序,我得到了一个要求,我有一个按钮的动作方法,当我点击按钮,我应该检索整个地址簿联系人和字符串的形式显示我如何做到这一点,任何人都可以告诉我的代码。这几天我没办法。
我不希望使用 ABPeoplePickerNavigationController
导航并访问它,我所需要的是点击按钮访问所有的联系方式,并以字符串的形式显示。
试试这个,它适用于iOS 6以及iOS 5.0或更早版本:
首先在Link Binary With Libraries 中添加以下框架- AddressBookUI.framework
- AddressBook.framework
他们进口
#import <AddressBook/ABAddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
然后使用以下代码
ABAddressBookRef addressBook = ABAddressBookCreate();
__block BOOL accessGranted = NO;
if (ABAddressBookRequestAccessWithCompletion != NULL) { // We are on iOS 6
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
accessGranted = granted;
dispatch_semaphore_signal(semaphore);
});
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_release(semaphore);
}
else { // We are on iOS 5 or Older
accessGranted = YES;
[self getContactsWithAddressBook:addressBook];
}
if (accessGranted) {
[self getContactsWithAddressBook:addressBook];
}
// Get the contacts.
- (void)getContactsWithAddressBook:(ABAddressBookRef )addressBook {
NSArray *arrayOfPeople = (__bridge_transfer NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
NSUInteger index = 0;
NSMutableArray *firstNames = [[NSMutableArray alloc] init];
for(index = 0; index <= ([arrayOfPeople count] - 1); index++){
ABRecordRef currentPerson = (__bridge ABRecordRef)[arrayOfPeople objectAtIndex:index];
NSString *currentFirstName = (__bridge_transfer NSString *)ABRecordCopyValue(currentPerson, kABPersonFirstNameProperty);
// If first name is empty then don't add to the array
if (![currentFirstName length] == 0) {
[firstNames addObject: currentFirstName];
}
}
//OPTIONAL: Use the following line to sort the first names alphabetically
NSArray *sortedFirstNames = [firstNames sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
NSLog(@"Total Count = %d n Sorted By Name = %@", [sortedFirstNames count], sortedFirstNames);
}
试试这个
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *people = (NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);
for(id person in people){
NSString *name = [NSString stringWithFormat:@"%@ %@",(NSString *)ABRecordCopyValue( person, kABPersonFirstNameProperty ),(NSString *)ABRecordCopyValue( person, kABPersonLastNameProperty )];
//fetch multiple phone nos.
ABMultiValueRef multi = ABRecordCopyValue(person, kABPersonPhoneProperty);
for (CFIndex j=0; j < ABMultiValueGetCount(multi); j++) {
NSString* phone = (NSString*)ABMultiValueCopyValueAtIndex(multi, j);
[numbersArray addObject:phone];
[phone release];
}
/fetch multiple email ids.
ABMultiValueRef multiemail = ABRecordCopyValue(person, kABPersonEmailProperty);
for (CFIndex j=0; j < ABMultiValueGetCount(multiemail); j++) {
NSString* email = (NSString*)ABMultiValueCopyValueAtIndex(multiemail, j);
NSLog(@"Email=%@",email);
}
}
,在使用之前必须分配数组。在viewDidLoad方法中为alloc数组写这个
numbersArray=[[NSMutableArray alloc] init];