func getContacts() {
let store = CNContactStore()
if CNContactStore.authorizationStatus(for: .contacts) == .notDetermined {
store.requestAccess(for: .contacts, completionHandler: { (authorized: Bool, error: NSError?) -> Void in
if authorized {
self.retrieveContactsWithStore(store: store)
}
} as! (Bool, Error?) -> Void)
} else if CNContactStore.authorizationStatus(for: .contacts) == .authorized {
self.retrieveContactsWithStore(store: store)
}
}
func retrieveContactsWithStore(store: CNContactStore) {
do {
let groups = try store.groups(matching: nil)
let predicate = CNContact.predicateForContactsInGroup(withIdentifier: groups[0].identifier)
//let predicate = CNContact.predicateForContactsMatchingName("John")
let keysToFetch = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName), CNContactEmailAddressesKey] as [Any]
let contacts = try store.unifiedContacts(matching: predicate, keysToFetch: keysToFetch as! [CNKeyDescriptor])
self.objects = contacts
DispatchQueue.main.async(execute: { () -> Void in
self.myTableView.reloadData()
})
} catch {
print(error)
}
}
我试图从地址簿中检索联系人,但每当我转到调用getContacts()的视图时,应用程序就会冻结。它不会继续下去,但它也没有崩溃。我想知道这里出了什么问题?
答案 0 :(得分:1)
您对requestAccess
的调用代码不正确。完成处理程序的语法无效。你需要这个:
func getContacts() {
let store = CNContactStore()
let status = CNContactStore.authorizationStatus(for: .contacts)
if status == .notDetermined {
store.requestAccess(for: .contacts, completionHandler: { (authorized: Bool, error: Error?) in
if authorized {
self.retrieveContactsWithStore(store: store)
}
})
} else if status == .authorized {
self.retrieveContactsWithStore(store: store)
}
}
另请注意使用status
变量的更改。与一遍又一遍地调用authorizationStatus
相比,这更清晰,更易于阅读。调用一次,然后根据需要反复检查值。