0

I am struggling to understand Swift closures, particularly how to get data out of them. The following code makes a http get request and retrieves data from a URL. Which all works fine. I can print out this data within the closure but cannot work out how store into an external variable or return the data. The routes variable is nil when the code completes. Does anyone know what I'm doing wrong and/or how to get the data out of the closure.

var routes: [String]?

let task = URLSession.shared.dataTask(with: url, completionHandler: { data, response, error in
    guard let data = data, error == nil else {
        print(error ?? "Unknown error")
        return
    } //end let
    do {
    if let jsonDict = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {
        if let response = jsonDict.value(forKey: "response") as? NSArray {
            for i in 0..<response.count {
                let route = response.object(at: i) as! NSDictionary
                print(route.value(forKey: "route_id")!)
                routes?.append(route.value(forKey: "route_id")! as! String)

            }
        self.routes = routes
        print(self.routes)
        }
    }
    } catch let error as NSError {
        print(error.localizedDescription)
    }
})
task.resume()

OUTPUT:

11201-20180605110613_v67.1

11202-20180524131340_v66.89

11201-20180524131340_v66.89

11202-20180605110613_v67.1

nil
Latika Agarwal
  • 973
  • 1
  • 6
  • 11
ozzyzig
  • 709
  • 8
  • 19

0 Answers0