我的应用中有以下网址发布请求,该请求能够获得有效的响应。但是,当我比较输入的原始字符串以响应var时,“ postResponse”为nil,即使我可以在先前的打印中看到它具有值。 Xcode 10.2.1 Swift 5
在do块中,打印命令显示从服务器返回的有关postResponse和postMessage的正确信息。这些命令在这里可以正常打印,但是在do块完成之后,随后的打印语句或对变量的任何比较都说它们为nil。
理想情况下,我希望能够将输入的内容与返回的内容进行比较,并继续执行相应的操作,但是现在最后一个代码块警报功能始终会被触发,因为postResponse在执行到该点时为零。
我在这里想念什么?
@IBAction func LoginBtn(_ sender: Any) {
//created NSURL
let requestURL = NSURL(string: URL_SERVICE)
//creating NSMutableURLRequest
let request = NSMutableURLRequest(url: requestURL! as URL)
//setting the method to post
request.httpMethod = "POST"
//getting values from text fields
let mode = "login"
let userid = EmployeeID.text
var postResponse : String?
var postMessage : String?
//creating the post parameter by concatenating the keys and values from text field
let postParameters = "mode="+mode+"&userid="+userid!;
//adding the parameters to request body
request.httpBody = postParameters.data(using: String.Encoding.utf8, allowLossyConversion: false)
//creating a task to send the post request
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
if error != nil{
print("error is \(String(describing: error))")
return;
}
//parsing the response
do {
//converting resonse to NSDictionary
let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
//parsing the json
if let parseJSON = myJSON {
//getting the json response
postResponse = (parseJSON["AppID"] as! String)
postMessage = (parseJSON["message"] as! String)
//username = parseJSON["username"] as! String?
print(postMessage!)
print(postResponse!)
}
} catch {
print(error)
}
}
task.resume()
print("userid \(String(describing: userid)) resp \(String(describing: postResponse))")
if userid != postResponse {
EmployeeID.text = ""
let alertController = UIAlertController(title: "Unrecognized EmployeeID \(login ?? "nada")", message: "Please re-type EmployeeID", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}else{
}
}
答案 0 :(得分:0)
postMessage
块完成后,postResponse
和do
在代码中为零的原因是,do
块中的代码尚未执行,因此,尚未设置其值。 do
块是异步调用的完成处理程序的一部分。