Go to another view when NSURLSession finishes its job

538 Views Asked by At

My problem is when I try to go another view after some api call finishes, it wont go to the next view. Here is the code below. Thanks in advance.

var task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: {
    (data, response, error) in //println(response)
    //println(error)
    self.myWeather.apiCallData = JSON(data: data)
    self.myWeather.apiCallError = error

    println("api call finished")

    if error == nil {
        println("no error")
        let weatherView = self.storyboard?.instantiateViewControllerWithIdentifier("WeatherView") as WeatherViewController
        weatherView.myWeather = self.myWeather
        self.navigationController?.pushViewController(weatherView, animated: false)
    }
}).resume()    

It does print api call finished and no error on console. But it doesn't go to the other scene.

1

There are 1 best solutions below

0
On BEST ANSWER

The problem is that the completion handler code of the dataTaskWithURL method runs in a background secondary thread, not in the main thread (where view controller transition can happen). Wrap the call to pushViewController in a main thread queue closure:

...
dispatch_async(dispatch_get_main_queue(), {

    let navigationVC = self.navigationController
    navigationVC?.pushViewController(weatherView, animated: false)
})
...

I have written the code in two lines to avoid a swift compiler bug (single statement and closure return value: see this). You can also write it as:

...
dispatch_async(dispatch_get_main_queue(), {
    (self.navigationController)?.pushViewController(weatherView, animated: false)
    return
})
...