我正在尝试获取用户联系人。一切正常,除了以下事实:当用户单击按钮以允许我们访问联系人时,联系人被打印在控制台中,但是到另一个viewcontroller的选择花费了很多时间,并且我的控制台输出像疯了似的说:
此应用程序正在从后台修改自动布局引擎 从主线程访问引擎后的线程
带有堆栈列表...
在阅读了关于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
}
}
答案 0 :(得分:1)
所有与UI相关的代码都需要在主线程上运行。在您的情况下,这是segue
DispatchQueue.main.async { [weak self] in
self?.performSegue(withIdentifier: "inviteFriends", sender: nil)
}