0

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

JulienCoo
  • 1,128
  • 3
  • 13
  • 24
  • Do not return, use a callback ("completion handler"). Just an example here: http://stackoverflow.com/a/35358750/2227743 and there's many others on SO. – Eric Aya Mar 24 '16 at 21:22

1 Answers1

1

You should implement Swift closure like that:

func getJsonDataFromPath(path: String, completion: (item: String)-> Void){

    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)")
        completion(item: videoId)
      }
    }

    task.resume()


  }

And its call:

override func viewDidLoad() {
      super.viewDidLoad()
      getJsonDataFromPath("http://coulon.xyz/JobX/APIs/getListOfJobs.php") { (test) -> Void in
        print("Value returned by getJsonDataFromPath: \(test)")
      }

    }
Muzahid
  • 5,072
  • 2
  • 24
  • 42