我需要从用户的通讯录中获取联系人并在skstableview中显示它。为了获取联系人并在表格视图中显示,我使用了下面的代码。但是,它既没有请求访问联系人权限,也没有获取联系人,并在控制台上打印以下语句:“Access Denied” UserInfo={NSLocalizedDescription=Access Denied, NSLocalizedFailureReason=This application has not been granted permission to access Contacts.}。 我已经在plist文件中添加了访问联系人的条目,但对我来说什么都不起作用。以下是我在Xcode 8.3.3中使用的代码片段,在swift中实现。
func getContacts() {
let store = CNContactStore()
if CNContactStore.authorizationStatus(for: .contacts) == .notDetermined {
store.requestAccess(for: .contacts){succeeded, err in
guard err == nil && succeeded else{
return
}
self.contactList()
}
} else if CNContactStore.authorizationStatus(for: .contacts) == .authorized {
self.contactList()
NSLog(" move to contact list ")
}
}
func contactList() {
let req = CNContactFetchRequest(keysToFetch: [
CNContactFamilyNameKey as CNKeyDescriptor,
CNContactGivenNameKey as CNKeyDescriptor,
CNContactPhoneNumbersKey as CNKeyDescriptor
])
arr_contacts.removeAllObjects()
try! CNContactStore().enumerateContacts(with: req) {
contact, stop in
print("contacts \(contact)") // in real life, probably populate an array
self.arr_contacts.add(contact)
}
tbl_List.reloadData()
print("added all contacts")
}
有人能建议我做错了什么吗?
谢谢
authorizationStatus
的值是什么?请求对话框会向用户显示吗?哪一行抛出了错误try! CNContactStore().enumerateContacts(with: req)
? - Dávid Pásztor.denied
并且你收到了错误,这意味着在你的代码中的其他地方,你正在调用未经授权检查的contactList
。你的问题中的代码似乎没有任何问题,因此错误很可能出现在其他地方。 - Dávid Pásztor