having hard time with UI updating with data from background thread. I read tons of docs but still missing something...
func getData(){
DispatchQueue.global(qos: .background).async {
let token = GetTokenOperation()
token.success = { item in
print("Success")
}
token.failure = {error in
print(error.localizedDescription)
}
NetworkQueue.shared.addOperation(op: token)
DispatchQueue.main.async {
// qos' default value is ´DispatchQoS.QoSClass.default`
self.updateUI()
}
}
}
self.updateUI() is executed before "Success" is printed. When I put self.updateUI() inside of the closure token.success it crashes indeed.
Have you tried this?
token.success = { item in
print("Success")
DispatchQueue.main.async {
self.updateUI()
}
}
in my case, i needed to update UI in background mode. I was a UIProgressView and timer. While time consuming, i updated progress view to show remaing time. But the user when clicked home button, app goes to bacground mode and UI will not update. To overcome this problem, i use DispatchQueue with .background option.
DispatchQueue.global(qos: .background).async {
DispatchQueue.main.async {
let fractionalProgress = Float(self.counter) / 60.0
let animated = self.counter != 0
self.barProgress.setProgress(fractionalProgress, animated: animated)
}
}
I hope, this will help someone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With