Reputation: 103
I am checking on a test Server if a user is registered. If the server gives back, that the username and password are true, i want to perform a Segue with the identifier "Login". If I put the performeSegue inside the URLSession dataTask the program crashes with this error: "terminating with uncaught exception of type NSException" I don't know what to do. because of the resume() function I can't put the performSegue outside of the dataTask. It would be executed before i get the data from the server.
Here is my Code:
@IBAction func login(_ sender: AnyObject) {
var session:String?
if userName.text!.isEmpty || logInPassword.text!.isEmpty{
let noUserName = UIAlertController(title: "Kein Benutzername oder Passwort", message: "Bitte geben sie einen Benutzernamen und ein Passwort ein.", preferredStyle: .alert)
noUserName.addAction(OKAction)
self.present(noUserName, animated: true)
} else {
//Implementing URLSession
let urlString = "http://www.***.me/playground/api/v1/user/login/\(userName.text!)/\(logInPassword.text!)"
guard let url = URL(string: urlString) else {
print("Error: couldn't open link")
return
}
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let responseData = data else {
print("Error: did not receive data")
return
}
//Implement JSON decoding and parsing
do {
//Decode retrived data with JSONDecoder and assing type of Article object
let personsData = try JSONDecoder().decode(LoginTest.self, from: responseData)
session = personsData.session
dump(personsData)
} catch let jsonError {
print("Error: \(jsonError)")
}
if session != nil{
//loging in
print("now loged in")
self.performSegue(withIdentifier: "Login", sender: self)
//here it crashes
} else {
let alertWrongPassword = UIAlertController(title: "Benutzername und Passwort stimmen nicht überein", message: "Bitte versuchen Sie es erneut.", preferredStyle: .alert)
alertWrongPassword.addAction(self.OKAction)
self.present(alertWrongPassword, animated: true)
}
}.resume()
//End implementing URLSession
}
}
Upvotes: 1
Views: 159
Reputation: 285059
According to the exception reason you have to perform the segue on the main thread
DispatchQueue.main.async {
self.performSegue(withIdentifier: "Login", sender: self)
}
Upvotes: 4