通过ABAddressBookCreate访问地址簿

时间:2017-02-13 10:30:56

标签: ios swift

我正在尝试访问地址簿:

var addressBook = ABAddressBookCreate() as! ABAddressBook!
if addressBook == nil {
    print("addressBook not available")
    return
}
var allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook)
var noOfPeople = ABAddressBookGetPersonCount(addressBook)

但我的代码总是崩溃

var allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook)

在控制台中没有任何错误。

什么是正确的方法?

谢谢

1 个答案:

答案 0 :(得分:0)

1:确保您已在plist中设置Privacy - Contacts Usage Description

2:当您尝试访问地址簿时,您需要具有权限,这是示例代码

let addressStatus: ABAuthorizationStatus = ABAddressBookGetAuthorizationStatus()
        if addressStatus == ABAuthorizationStatus.notDetermined {
            let addressBook: ABAddressBook? = ABAddressBookCreate().takeRetainedValue()
            if let addressBookRef = addressBook {
                ABAddressBookRequestAccessWithCompletion(addressBookRef, { (granted, error) in
                    if granted {
                        //read address book
                    } else {
                        //do something without grant, toast or alert
                    }
                })
            } else {
                //fail 
            }
        } else if addressStatus == ABAuthorizationStatus.authorized {
            //already have the authority
            let addressBook: ABAddressBook? = ABAddressBookCreate().takeRetainedValue()
            if let addressBookRef = addressBook {
                //read address book
            } else {
                //fail
            }
        } else {
            //no authority
        }