3

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()
            }
        }
    }
bdash
  • 18,110
  • 1
  • 59
  • 91
ayjoy
  • 155
  • 3
  • 10

1 Answers1

11

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

}
Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223