У меня есть следующий запрос на публикацию URL в моем приложении, который может получить действительный ответ.Однако, когда я сравниваю исходную строку, введенную в ответ, переменная "postResponse" равна нулю, хотя я вижу, что она имеет значение в предыдущей печати.Xcode 10.2.1 Swift 5
В блоке do команды печати показывают правильную информацию, возвращаемую с сервера как для postResponse, так и для postMessage.Они хорошо печатаются здесь, но позже, после завершения блока do, последующие операторы print ИЛИ любое сравнение переменных говорят, что они равны 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{
}
}