OStack程序员社区-中国程序员成长平台

标题: ios - 访问 ABAddressBook 时出错 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 08:54
标题: ios - 访问 ABAddressBook 时出错

我正在使用以下代码访问 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

为什么error不为零?我的代码有什么错误吗?在发生真正错误的情况下,如何检测并停止尝试访问地址簿?



Best Answer-推荐答案


感谢 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
}

关于ios - 访问 ABAddressBook 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31200787/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4