简体   繁体   English

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

[英]SWIFT2.0: function returns before task is completed

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. 我建立了一个在线解析JSON文件的功能。 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". 解析完文件后,该函数应返回String,但是它不等待任务完成才返回。 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 getJsonDataFromPath返回的值:++空++ HTTP响应:200 videoId为:kzv1NQGdsyk

How can i make sure task.resume is completed before returning the value ? 如何在返回值之前确保task.resume已完成?

Thank a lot in advance, 在此先多谢

Regards, Julien 问候,朱利安

You should implement Swift closure like that: 您应该像这样实现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()


  }

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)")
      }

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 解析完成前遇到Stream结束? - End of Stream encountered before parsing was completed? 在处理完成之前已达到流结束 - The stream-end was reached before the processing is completed 序列化异常,解析完成之前遇到流尾 - Serialization Exception, End of Stream encountered before parsing was completed 反序列化压缩字符串时出错(解析完成之前遇到的Stream End)C# - Error in deserializing a compressed string (End of Stream encountered before parsing was completed) C# 通过TCP发送大对象:“解析完成之前遇到的流结束” - Sending large objects over TCP: “End of Stream encountered before parsing was completed” 在Spark RDD操作中使用类方法返回无法序列化的任务异常 - Using Class Methods in Spark RDD Operations Returns Task not serializable Exception Spark 任务无法使用滞后窗口功能进行序列化 - Spark Task not serializable with lag Window function apry spark中的类(task对象)的kryo序列化在反序列化时返回null - kryo serializing of class (task object) in apache spark returns null while de-serialization 原型序列化返回函数,而不是序列化的字符串 - prototype serialize returns function instead of serialized string 在Unity中的“ OnAfterDeserialize”之前是否有一个被调用的类或函数? - Is there a class or function called right before 'OnAfterDeserialize' in Unity?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM