ios - Returning values URLSession.shared.dataTask in swift -


this question has answer here:

i started coding in swift , have following code parses json

func parse (latitude: double, longtitude: double){       let jsonurlstring = "https://api.darksky.net/forecast/apikey/\(latitude),\(longtitude)"      guard let url = url(string: jsonurlstring) else{         return     }      var information: forecast?     urlsession.shared.datatask(with: url) { (data, res, err) in          guard let data = data else {                return         }          {             let json = try jsondecoder().decode(forecast.self, from: data)             self.info = json          } catch {             print("didnt work")         }      }.resume()      processjson(info) } 

my problem want pass data stored in json variable in class processed using processjson function since datatask function not return values, , json variable locally stored cannot process info variable outside class (it returns nil). wondering solution problem? i'm facing same problem weather.getcoordinate().

you can use completion block return value. add completion block function this

func parse (latitude: double, longtitude: double, completion: @escaping ((anyobject) -> void)){     let jsonurlstring = "https://api.darksky.net/forecast/apikey/\(latitude),\(longtitude)"      guard let url = url(string: jsonurlstring) else{         return     }      var information: forecast?     urlsession.shared.datatask(with: url) { (data, res, err) in          guard let data = data else {                return         }          {             let json = try jsondecoder().decode(forecast.self, from: data)             self.info = json             completion(info)         } catch {             print("didnt work")         }      }.resume() 

and when call function, return info

parse( lat, long, {info in processjson(info) })


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -