I'm pretty sure this is easy for most of you, but i'm a beginner and i cannot figure this one out.
I build a function to parse a JSON file online. That function should returns a String once the file has been parsed, but it does not wait for the task to be completed before "return". Therefore, i always end up with a wrong value.
my function:
func getJsonDataFromPath(path: String) -> String {
var videoId: String
videoId = "++ empty ++"
let url = NSURL(string:path)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
if let httpResponse = response as? NSHTTPURLResponse {
print("HTTP RESPONSE: \(httpResponse.statusCode)")
} // END OF if let httpResponse = response as? NSHTTPURLResponse
let json = JSON(data: data!)
// print(json)
if (json.count > 0) {
videoId = json[0]["videoId"].string!
print("videoId is: \(videoId)")
}
}
task.resume()
return videoId
}
and its call:
override func viewDidLoad() {
super.viewDidLoad()
let test = getJsonDataFromPath("http://coulon.xyz/JobX/APIs/getListOfJobs.php")
print("Value returned by getJsonDataFromPath: \(test)")
}
I always get the output in the wrong order:
Value returned by getJsonDataFromPath: ++ empty ++ HTTP RESPONSE: 200 videoId is: kzv1NQGdsyk
How can i make sure task.resume is completed before returning the value ?
Thank a lot in advance,
Regards, Julien