我试着去获取一个用户的联系人。一切运作良好,除了一个事实,即当按钮用户点击允许我们访问联系人,联系人获取控制台打印出来,但SEGUE到其他视图控制器使用了大量的时间,我的控制台输出会像疯了似的说法:
本申请修改从后台线程的自动布局引擎发动机从主线程访问后
与堆叠中的列表...
阅读StackOverflow上的错误后,我发现我需要一个DispatchQueue.main.async()。但是我不能真正把它放在哪里?有人能解释一下?
这是为动作出口,当按下该按钮的代码,其中所述错误发生:
@IBAction func didTapFindContacts(_ sender: Any) {
fetchContacts()
}
func fetchContacts() {
contactStore.requestAccess(for: .contacts) { (success, error) in
if let error = error {
print("failed to request access:", error)
return
}
if success {
self.performSegue(withIdentifier: "inviteFriends", sender: nil)
let contactStore = CNContactStore()
let keys = [CNContactGivenNameKey,
CNContactPhoneNumbersKey,
CNContactFamilyNameKey] as [Any]
let request = CNContactFetchRequest(keysToFetch: keys as! [CNKeyDescriptor])
do {
try contactStore.enumerateContacts(with: request){ (contact, stop) in
// Array containing all unified contacts from everywhere
let name = contact.givenName
let familyName = contact.familyName
let number = contact.phoneNumbers.first?.value.stringValue
let contactsAppend = ContactStruct(givenName: name, familyName: familyName, number: number!)
self.contacts.append(contactsAppend)
print(name)
}
} catch {
print("unable to fetch contacts")
}
}
//go to other page
}
}
这涉及到UI所有代码需要在主线程上运行。在你的情况下,它是一个SEGUE
DispatchQueue.main.async { [weak self] in
self?.performSegue(withIdentifier: "inviteFriends", sender: nil)
}