我正在使用以下代码访问ABAddressBook:
+ (void)connectToAddressBook {
if(!_addressBook)
{
CFErrorRef error;
_addressBook = ABAddressBookCreateWithOptions(NULL, &error);
NSLog(@"Address book %@", _addressBook);
if (error != nil) {
NSLog(@"ERROR WHILE ACCESSING ADDRESS BOOK: %@", CFBridgingRelease(error));
CFRelease(error);
}
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(_addressBook, ^(bool granted, CFErrorRef error) {
_isAccessToContactsAllowed = granted;
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
_isAccessToContactsAllowed = YES;
}
else {
_isAccessToContactsAllowed = NO;
}
}
}
地址簿打开正常,但由于某种原因错误不是nil并记录当前类的名称:
ERROR WHILE ACCESSING ADDRESS BOOK: MyContactManager
为什么错误不是零?我的代码有点错吗?如果出现真正的错误,如何检测并停止尝试访问地址簿?
答案 0 :(得分:1)
感谢来自Ilesh的反馈,这是我的固定方法:
+ (void)connectToAddressBook {
if(!_addressBook) {
CFErrorRef *error = nil;
_addressBook = ABAddressBookCreateWithOptions(NULL, error);
// To test if error is not nil:
//error = CFErrorCreate(NULL, CFSTR("Hello, world."), 111, NULL);
if (error != nil) {
NSLog(@"ERROR WHILE ACCESSING ADDRESS BOOK: %@", CFBridgingRelease(error));
CFRelease(error);
}
else {
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(_addressBook, ^(bool granted, CFErrorRef error) {
_isAccessToContactsAllowed = granted;
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
_isAccessToContactsAllowed = YES;
}
else {
_isAccessToContactsAllowed = NO;
}
}
}
}
修改强>
看来我最初的错误是没有将错误分配给 nil 。地址簿创建不会设置错误除非确实存在错误。所以我的未分配变量指向内存中的一些随机位置,这就是我第一次尝试时出现随机错误的原因。
更重要的是,如果出现错误,ABAddressBookCreateWithOptions将返回 nil ,因此正确的方法是:
if(_addressBook) {
// do something
}
else {
// there is an error
}
答案 1 :(得分:0)
将您的整个代码替换为此
+ (void)connectToAddressBook {
if(!_addressBook)
{
_addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(addressBook,
^(bool granted, CFErrorRef error) {
if (granted)
dispatch_async(dispatch_get_main_queue(), ^{
_isAccessToContactsAllowed = granted;
});
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
dispatch_async(dispatch_get_main_queue(), ^{
_isAccessToContactsAllowed = YES;
});
}
else {
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:Nil message:@"You don't have permission of access contacts for access go to Setting-" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
}}