swift - swift 中的 “This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread”

标签 swift xcode dispatch-async cncontact

我正在尝试获取用户联系人。一切正常,除了当用户点击按钮允许我们访问联系人时,联系人会在控制台中打印出来,但是到另一个 viewcontroller 的 segue 使用了很多时间,我的控制台输出就像疯了似的说:

This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread

带有堆栈列表...

阅读 StackOverflow 上的错误后,我发现我需要一个 DispatchQueue.main.async()。但是我真的不知道把它放在哪里?有人可以向我解释吗?

这是 action outlet 的代码,当按钮被按下时,错误发生的地方:

@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)
}

关于swift - swift 中的 “This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54553421/

相关文章:

ios - 添加分享按钮 - Swift

ios - 不遵循 QoS 优先级的队列

ios - 将图像从 Web 服务加载到 UIImage 无法正常工作

ios - ASIHTTPREQUEST 无内容长度响应(大型 PDF 文件)

ios - 按下按钮时应用程序崩溃

ios - 删除带有 CoreData 和 NSFetchedResultsController 的 UITableView 行

ios - 如何在 xcode 中修复 "Failed to load model named datamodelname"

ios - 如何获取 XCode 应用程序的日志

ios - 在 swift 3 中使用 NotificationCenter 停止 Dispatchqueue

ios - 当数组有数据时在 Swift 中解析返回空数组