swift中的do-catch范围 - 不能为外部变量赋值

时间:2016-07-10 19:04:43

标签: swift scope swift2 nsjsonserialization do-catch

我已经制作了一些代码来向我的php脚本发出POST请求,该脚本放在我的服务器上。我已经测试过,那部分工作正常。我从服务器返回结果时遇到了问题 - 我以JSON格式获取它,并在do-catch语句中打印 - 确定。我将返回变量赋给变量,该变量在do-catch外部声明,而不是“可见”。让我展示我的代码,当你看到代码时解释起来会更简单:

//sending inputs to server and receiving info from server
    let json:[String:AnyObject] = [ "username" : username!, "password" : password!, "iphone" : "1" ]
    var link = "http://www.pnc.hr/rfid/login.php"
    var novi:String = ""

        do {
            let jsonData = try NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted)

            // create post request
            let url = NSURL(string: link)!
            let request = NSMutableURLRequest(URL: url)
            request.HTTPMethod = "POST"

            // insert json data to the request
            request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
            request.HTTPBody = jsonData

            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
            request.addValue("application/json", forHTTPHeaderField: "Accept")


            let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
                if error != nil{
                    print("Error 55 -> \(error)")
                    return
                }

                do {
                    let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]
                    print("FIRST PRINT -> \(result!["password"])")
                    novi = String(result!["password"])
                    //return result
                } catch {
                    print("Error  43-> \(error)")
                }
            }
            task.resume()
        }
        catch {
            //handle error. Probably return or mark function as throws
            print(error)

        }

    print("SECOND PRINT -> \(novi)")

如果你看到print("FIRST PRINT -> \(result!["password"])") - 它会正常执行并输出所有变量。然后,如果你在代码的末尾看到print("SECOND PRINT -> \(novi)"),它会输出空的刺 - 就像我没有为它分配变量一样。

1 个答案:

答案 0 :(得分:0)

您正在使用异步块。 print块将在你的块有机会设置novi之前运行。

这个问题不是do-catch的问题,它是一个异步问题。