Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift3 - update ui with data from background

Tags:

swift3

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.

like image 969
BobC Avatar asked Aug 22 '16 14:08

BobC


2 Answers

Have you tried this?

    token.success = { item in
        print("Success")
        DispatchQueue.main.async {
            self.updateUI()
        }
    }
like image 138
OOPer Avatar answered Nov 16 '22 22:11

OOPer


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.

like image 21
Emre Gürses Avatar answered Nov 16 '22 23:11

Emre Gürses