I'm trying to make background api call and update UI when it returns the result, I've check GCD documentation.
Is there a problem with logic below?
// get data from server
let priority = DISPATCH_QUEUE_PRIORITY_BACKGROUND
dispatch_async(dispatch_get_global_queue(priority, 0)) {
self.getUserData() // update self.data1 global variable
self.getCompanyData() // update self.data2 global variable
dispatch_async(dispatch_get_main_queue()) {
self.updateUI() //update UI using self.data1 and self.data2 global variable
}
}
func getUserData(){
... api1 call
... print("1")
}
func getCompanyData(){
... api2 call
... print("2")
}
func updateUI(){
... print("UI")
}
When it executes, output is basically;
UI
1
2
I would like to call updateUI function after api both of api calls are finished.
one of the api call function below;
let fullUrl = self.apiDomain + "/user_details/" + String(self.user_id)
let url:NSURL = NSURL(string: fullUrl)!
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "GET"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
let task = session.dataTaskWithRequest(request) {
(
let data, let response, let error) in
guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
print(error)
return
}
var apiCallResult: [String:AnyObject]?
let result = NSString(data: data!, encoding: NSUTF8StringEncoding)
do {
apiCallResult = try NSJSONSerialization.JSONObjectWithData(result!.dataUsingEncoding(NSUTF8StringEncoding)!, options: []) as? Dictionary<String, AnyObject>
} catch let error as NSError {
print(error.localizedDescription)
return
}
let aa = apiCallResult!["data"]! as! NSDictionary
print(aa)
}
task.resume()
getUserData()andgetCompanyData()do not work asynchronously.