Search code examples
iosswiftrequestresponsealamofire

How to load view controller (or invoke segue) after response gets loaded(using Alamofire)?


I'm a newbie to swift

I have several buttons on 1st View Controller. I'm making different request to server for each button click (from 1st ViewController using Alamofire) & only when I get the response from server as JSON, the 2nd ViewController should be loaded (further I'd dynamically populate the controls on 2nd ViewController by parsing the response JSON data).

My issue is the 2nd View Controller gets loaded up with old data(before response gets loaded for that button click).

My Scenario: (swift 3)

  • When I click the ButtonA ,go back and again click ButtonA - data for ButtonA gets displayed properly
  • When I click ButtonA, go back and click ButtonB - data for ButtonA gets displayed wrongly

Excuse for not having posted the code(due to some restrictions in workplace). Thanks in advance


Solution

  • You can pass son data received from server in sender parameter of performSegue like this :

    let jsonDataReceived = /*Returned data from server (Array or Dictionary )*/
        self.performSegue(withIdentifier: "YOUR_SEGUE_ID", sender: jsonDataReceived)
    

    then prepare for segue method you can retrieve your data object :

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "YOUR_SEGUE_ID" {
            let jsonDataReceived = sender as? //(Array or Dictionary )
            /* intialize you viewController data with jsonDataReceived*/
        }
    }