I am trying to validate the login of a user with my database. When the login button is pressed I want to say whether a segue will happen or no based on the info returned back from the database. I start with a variable decision set to true initially and if the I can't validate the user I want to set it to false and prevent segue. This is the code that I have, but there is a problem with it. The return statement at the end is always true. What happens basically is the return statement at the end after .resume() get called first before the response is returned from the database. Can someone clarify why this is happening
override func shouldPerformSegue(withIdentifier identifier: String,sender:
Any?) -> Bool
{
var decision = true
let url = URL(string:"http://192.23.25.98/login/php")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
let body = "UserNameLogIn=(userName.text!.lowercased())&PasswordLogIn=(passWord.text!.lowercased())"
request.httpBody=body.data(using: String.Encoding.utf8)
URLSession.shared.dataTask(with: request) { (data:Data?, response:URLResponse?, error:Error?) in
if (error == nil)
{
DispatchQueue.main.async(execute: {
do
{
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? Dictionary<AnyHashable,AnyObject>
guard let parseJson = json else{
print ("error parsing")
return
}
let status = parseJson["status"]
if (status != nil)
{
if (parseJson.count>3)
{
decision = true
}
else
{
decision = false
}
}
}
catch
{
print("error: (error)")
}
})
}
else
{
decision = false
}
}.resume()
return decision
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…