简体   繁体   English

如何在 Swift 中将任务发送到后台队列?

[英]How to send tasks to the background queue in Swift?

I have a local notification that is set when a user taps a button.我有一个当用户点击按钮时设置的本地通知。 I want to send this to the background thread and then update the UI.我想将其发送到后台线程,然后更新 UI。 Is this a safe way to do it?这是一种安全的方法吗?

    DispatchQueue.global(qos: .background).async { // sends registration to background queue
        center.add(request, withCompletionHandler: {(error) in
            if let error = error {
                print(error)
            }
        })
        DispatchQueue.main.async {
            try! self.realm.write {
                self.realm.add(task)
                self.updateData()
            }
        }
    }

You should move the main thread block inside the completion handler and use a do/catch block when writing to the Realm DB.您应该在完成处理程序中移动主线程块,并在写入 Realm DB 时使用 do/catch 块。 Otherwise, your code seems fine.否则,您的代码看起来不错。

IMPORTANT: use [weak self] inside the DispatchQueue block if you're not in a singleton.重要提示:如果您不是单身人士,请在 DispatchQueue 块中使用[weak self] More details here.更多细节在这里。

DispatchQueue.global(qos: .utility).async { // sends registration to background queue
    center.add(request) { error in
        if let error = error {
            print(error)
        } else {
            DispatchQueue.main.async {
                do {
                    try self.realm.write {
                        self.realm.add(task)
                        self.updateData()
                    } catch {
                        print("Error while writing to the Realm DB:", error)
                    }
                }
            }
        }
    })

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM