我的应用程序中有以下网址发布请求,可以获得有效的响应。但是,当我将输入的原始字符串与响应进行比较时,var“postResponse”为nil,即使我可以看到它在先前的打印中有值。Xcode 10.2.1 Swift 5
在do块中,print命令显示从服务器返回的postResponse和postMessage的正确信息。这些打印在这里打印很好,但是在do块完成之后,随后的打印语句或任何变量的比较表明它们是零。
理想情况下,我希望能够将输入的内容与返回的内容进行比较并继续相应地执行,但是现在最后一个代码块警报函数总是被触发,因为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{
}
}
发布于 2019-06-27 14:32:48
其理由postMessage
和postResponse
在代码零后的do
块完成是因为在码do
块还没有被执行,并且因此,还没有设定它们的值。该do
块是异步调用的完成处理程序的一部分。
https://stackoverflow.com/questions/-100007064
复制相似问题