NSURLSession如何正常工作?

时间:2016-09-20 12:17:31

标签: ios swift2 nsurlsession

以下代码行写在函数内部,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()

与查询相关的输出是:( session_id和session_name初始化为随机值1和a)

values are 1 and a

然后它打印:(来自php脚本的响应中的两个变量的值)

values1 are ckj0uuj2q18m97m78m1uvje7f5 and d72d1363f44031cac4148b0e6fa295d6

我的疑问是'print stmt 1'之前打印的'print stmt 2'怎么样?我是新手。我在这里错过了任何概念吗? 另外,为什么'print stmt 2'打印变量的初始值而不是新值?我知道这两个问题是相关的,但我没有得到如何

1 个答案:

答案 0 :(得分:0)

大块中的代码(Swift称之为闭包)在请求完成后运行。没有办法立即通过互联网获取价值,因为它可能需要长达90秒,而且您不希望整个应用程序被阻止这么长时间(特别是因为iOS会在30之后彻底终止您的应用)。

解决这个问题的方法是更改​​需要值的代码,以便它提供在检索到值后运行的代码,以便对这些值执行某些操作。

有关详细信息,请参阅https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html