SWIFT2.0:函数在任务完成之前返回

时间:2016-03-24 21:16:18

标签: serialization swift2

我很确定这对你们大多数人来说都很容易,但我是初学者,我无法想出这一点。

我构建了一个在线解析JSON文件的函数。一旦解析了文件,该函数应返回一个String,但它不会等待“return”之前完成任务。因此,我总是以错误的价值结束。

我的职能:

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   

}

及其电话:

override func viewDidLoad() {
    super.viewDidLoad()

    let test = getJsonDataFromPath("http://coulon.xyz/JobX/APIs/getListOfJobs.php")
    print("Value returned by getJsonDataFromPath: \(test)")
}

我总是以错误的顺序得到输出:

getJsonDataFromPath返回的值:++ empty ++ HTTP响应:200 videoId是:kzv1NQGdsyk

如何在返回值之前确保task.resume已完成?

提前多多感谢,

此致 于连

1 个答案:

答案 0 :(得分:1)

你应该像这样实现Swift闭包:

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()


  }

并致电:

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

    }