简体   繁体   中英

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. 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. Otherwise, your code seems fine.

IMPORTANT: use [weak self] inside the DispatchQueue block if you're not in a singleton. 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)
                    }
                }
            }
        }
    })

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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