我正在使用Swift 4.2和Xcode 10.2.1。
在出现并授予“联系人”权限请求后,我需要帮助重新加载表格视图。当前,对话框显示首次请求使用权限,但是在第一次使用期间获得许可后,不会重新加载表格视图。如果我关闭应用程序并重新打开,则联系人将按预期显示(换句话说,当未显示请求权限对话框时,它会显示正常)。这是我的代码:
在viewDidLoad
的{{1}}中:
ContactsViewController
在 // Load the contacts from the phone
ContactService.fetchContacts(completion: { (contacts) in
if contacts != nil {
self.deviceContacts = contacts!
self.tableView.reloadData()
}
})
中:
ContactService
我尝试在static func fetchContacts(completion: @escaping (_ contacts: [Contact]?) -> Void) {
var deviceContacts:[Contact] = [Contact]()
// Set up default storage for the contacts
let store = CNContactStore()
// Request access to the contacts if not already given.
store.requestAccess(for: .contacts) { (granted, error) in
if let error = error {
print("Failed to request access:", error)
completion (nil)
}
if granted {
print("Access granted.")
// Information to retrieve
let keys = [CNContactIdentifierKey, CNContactGivenNameKey, CNContactFamilyNameKey, CNContactNicknameKey, CNContactNameSuffixKey, CNContactOrganizationNameKey, CNContactPhoneNumbersKey, CNContactImageDataAvailableKey, CNContactImageDataKey]
let request = CNContactFetchRequest(keysToFetch: keys as [CNKeyDescriptor])
// Sort by last name
request.sortOrder = CNContactSortOrder.familyName
do {
try store.enumerateContacts(with: request
, usingBlock: { (contact, stopPointerifYouWantToStopEnumerating) in
// Got the contacts from the device, now format as a Contact and put them into our array
let formattedContact = Contact(contactDetails: contact, favoriteNumbers: [], opened: false)
deviceContacts.append(formattedContact)
})
} catch let error {
print("Failed to enumerate contacts:", error)
}
} else {
print ("Access denied.")
completion (nil)
}
}
completion(deviceContacts)
}
的完成中将dispatchGroup.enter()
和.leave()
放在if granted
和.notify
内,但是没有用。
答案 0 :(得分:1)
您需要更改completion
的位置
try store.enumerateContacts(with: request
, usingBlock: { (contact, stopPointerifYouWantToStopEnumerating) in
// Got the contacts from the device, now format as a Contact and put them into our array
let formattedContact = Contact(contactDetails: contact, favoriteNumbers: [], opened: false)
deviceContacts.append(formattedContact)
})
completion(deviceContacts)
目前应该从store.requestAccess(for: .contacts) { (granted, error) in
中检索联系人,而且这里不需要调度组,因为它是一个异步任务,数量不多
requestAccess
的结果发生在后台线程中,因此请考虑
DispatchQueue.main.async {
self.tableView.reloadData()
}