Swift asynchronous web calls

Swift asynchronous web calls

I have written in the past about retrieving xml from asynchronous web service calls in Android Studio. In XCode / Swift there is no need to set up an entire class as an async task to retrieve data.

You can interrupt viewDidLoad, retrieve your JSON data (including handling errors such as no connection) then resume your task like this:

let url = URL(string: “https://yourwebservice”)!
let task = session.dataTask(with: url, completionHandler: {
            (data, response, error) in
               if error != nil {
  print(error!.localizedDescription)
 } else {
     do {
// deal with returned data here
        } catch {
           print(“error in JSONSerialization”)
        }
     }
  })
  task.resume()

There is a robust error catching mechanism here so you can present information about failures very easily.

Leave a Reply

Your email address will not be published. Required fields are marked *

For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.