简体   繁体   English

NSURLSession到底如何工作?

[英]How does NSURLSession exactly work?

The following lines of code are written inside a function and session_id and session_name are global variables. 以下代码行写在一个函数内,session_id和session_name是全局变量。

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
        guard let _:NSData = data, let _:NSURLResponse = response  where error == nil else {
            print("error")
            return
        }
        let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("dataString1 = \(dataString)")
        var json = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
        if(error != nil) {
            let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("Error could not parse JSON: '\(jsonStr)'")
            print(error)
        }
        else
            if let parseJSON = json {
                print("jsonstr = \(json)")
                if let success = parseJSON["success"] as? String {
                    if success == "true" {
                        let session_valid = parseJSON["session_valid"] as! String
                        if session_valid == "true"{
                            let response = parseJSON.objectForKey("response") as! NSDictionary
                            print("response = \(response)")
                            session_id = response.objectForKey("session_id") as! String
                            session_name = response.objectForKey("session_name") as! String
                            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                                if let resultController = self.storyboard!.instantiateViewControllerWithIdentifier("splitViewController") as? UISplitViewController {
                                    self.presentViewController(resultController, animated: true, completion: nil)
                                }
                            })
                        }
                    }
                }
                print("values1 are \(session_id) and \(session_name)") //print stmt 1
                return
            }//if
            else {
                print("json not parsed")
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("Error could not parse JSON: \(jsonStr)")
                print(error)
        }//else
    }
    print("values are \(session_id) and \(session_name)") //print stmt 2
    task.resume()

The output relevant to the query is: (session_id and session_name are initialised to random values 1 and a) 与查询相关的输出为:(session_id和session_name初始化为随机值1和a)

values are 1 and a

and then it prints: (values of the two variables in the response from the php script) 然后打印:(PHP脚本响应中两个变量的值)

values1 are ckj0uuj2q18m97m78m1uvje7f5 and d72d1363f44031cac4148b0e6fa295d6

My query is that how is 'print stmt 2' printed before 'print stmt 1'? 我的疑问是,如何在“ print stmt 1”之前打印“ print stmt 2”? I am new to swift. 我是新手。 Am I missing any concept here? 我在这里错过任何概念吗? Also, why does 'print stmt 2' print the initial values of the variables and not the new values? 另外,为什么“ print stmt 2”会打印变量的初始值而不是新值? I know the two questions are related but I am not getting how 我知道这两个问题是相关的,但我不知道如何

The code inside that big block (Swift calls it a closure) gets run after the request completes. 请求完成后,将运行该大块(Swift称为闭包)中的代码。 There's not a way to get a value over the Internet immediately, because it can take up to 90 seconds, and you don't want your entire app blocked for that long (particularly because iOS will kill your app outright after 30). 无法通过互联网立即获得价值,因为这可能需要90秒钟,而且您也不想整个应用都被阻止那么长时间(特别是因为iOS在30秒后会彻底杀死您的应用)。

The way you solve that is by changing the code that needs the values so that it provides code to run after the values have been retrieved, to do something with those values. 解决该问题的方法是更改​​需要这些值的代码,以便它提供在获取值后运行的代码,以对这些值进行处理。

See https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html for more info. 有关更多信息,请参见https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM