Search code examples
iosswiftsegue

perform segue after webservice


Hi I am failry new to iOS development and wanted to know if there is a equivalent of asynctask in iOS? I want my web service to finish and then I want to pass the contents of my web service to nextview controller

@IBAction func searchAction(_ sender: Any) {

    let airportName: String = airportCode.text!
    let minutesBefore: String = minutesBehind.text!
    let minutesAfter: String = minutesAhead.text!

    //web service request

    self.data = FlightWebService().getFlightData(airportCode: airportName, minutesBehind: minutesBefore, minutesAhead: minutesAfter)
    print(self.data)


    //how to pass data to the next view controller
    performSegue(withIdentifier: "goToSearch", sender: self)
}

Solution

  • You Can use URLSession available from ios 7.0 and later.

    In your method you can run async task

    func searchAction() {
        let defaultSessionConfiguration = URLSessionConfiguration.default
        let defaultSession = URLSession(configuration: defaultSessionConfiguration)
    
        let url = URL(string: "typeHereYourURL")
        var urlRequest = URLRequest(url: url!)
    
        let params = ""// json or something else
        let data = params.data(using: .utf8)
    
        urlRequest.httpMethod = "POST"
        urlRequest.httpBody = data
    
        let dataTask = defaultSession.dataTask(with: urlRequest) { (data, response, error) in
            performSegue(withIdentifier: "YourVCIdentifier", sender: self)
        }
    
        dataTask.resume()
    }
    

    or you can create serial queue and run FlightWebService request in another thread

    func searchAction() {
        let newQueue = DispatchQueue(label: "queue_label")
        newQueue.async {
            self.data = FlightWebService().getFlightData(airportCode: airportName, minutesBehind: minutesBefore, minutesAhead: minutesAfter)
            print(self.data)
    
            DispatchQueue.main.async {
                performSegue(withIdentifier: "YourVCIdentifier", sender: self)
            }
        }
    }
    

    and override this to send parameters to the next ViewController

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "YourVCIdentifier" {
            if let destinationVC = segue.destination as? YourVC {
                destinationVC.exampleStringProperty = //send data here recived earlier
            }
        }
    }