[英]Issue in fetching iPhone contacts from iOS SDK
我正在我的应用程序中获取iPhone联系人列表,为此我制作了一个示例应用程序并打印了它的值,并且效果很好。
ABAddressBookRef ab=ABAddressBookCreate();
NSArray *arrTemp=(NSArray *)ABAddressBookCopyArrayOfAllPeople(ab);
NSLog(@"Array===%@",arrTemp);
NSMutableArray *arrContact=[[NSMutableArray alloc] init];
for (int i=0;i<[arrTemp count];i++)
{
NSMutableDictionary *dicContact=[[NSMutableDictionary alloc] init];
NSString *str=(NSString *) ABRecordCopyValue([arrTemp objectAtIndex:i], kABPersonFirstNameProperty);
@try
{
[dicContact setObject:str forKey:@"name"];
}
@catch (NSException * e) {
[dicContact release];
continue;
}
[arrContact addObject:dicContact];
[dicContact release];
}
NSLog(@"arrContact===%@",arrContact);
我还使用了另一个代码来尝试其他方法,并且在示例中对我也很好。
CFErrorRef *error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBook);
for(int i = 0; i < numberOfPeople; i++) {
ABRecordRef person = CFArrayGetValueAtIndex( allPeople, i );
NSString *firstName = (NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
NSString *lastName = (NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
NSLog(@"Name:%@ %@", firstName, lastName);
ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
//NSLog(@"\n%@\n", [[UIDevice currentDevice] name]);
for (CFIndex i = 0; i < ABMultiValueGetCount(phoneNumbers); i++)
{
NSString *phoneNumber = (NSString *) ABMultiValueCopyValueAtIndex(phoneNumbers, i);
NSLog(@"phoneNumber======%@",phoneNumber);
}
}
它们在模拟器上可以正常工作,但是当我在设备上运行这些代码时,奇怪的是有时它们不提供详细的联系信息,但大多数情况下它们可以正常运行。 我的编码有什么问题吗?
当我在主应用程序中使用此演示代码时,该代码将永远不会响应。 我的设备中是否有针对不同应用程序的任何权限或任何设置?
另外,当我使用CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBook);
要获得人数,则其值为11,但我在模拟器上仅使用了五个联系人,当我使用CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
那么我将得到重复的值(以满足来自5个联系人的11个计数)。
有人可以告诉我这是怎么回事吗?
从iOS6开始,您需要用户权限才能从通讯簿访问联系人。 您也不需要征求许可。 可能是由于您没有联系。 我在我的应用中使用过的这段代码(由其他人编写)
+ (BOOL)getAccessPermission
{
__block BOOL accessGranted = NO;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
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;
}
return accessGranted;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.