我已经编写了一些代码来向放置在我的服务器上的 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)")
在代码末尾看到它会输出空字符串 - 就像我没有为它分配变量一样。