iosswiftmultithreadingios-multithreading

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

Solution

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