![](/img/trans.png)
[英]URLSession.shared.dataTask can't download image with swedish url
[英]performSegueWithIdentifier while in URLSession.shared.dataTask(with: url)
我正在測試服務器上檢查用戶是否已注冊。 如果服務器返回,則用戶名和密碼為true,我想使用標識符“ Login”執行Segue。 如果我將performeSegue放在URLSession dataTask內,程序將因以下錯誤而崩潰:“終止為NSException類型的未捕獲異常”,我不知道該怎么辦。 由於resume()函數的原因,我不能將performSegue放在dataTask之外。 它會在我從服務器獲取數據之前執行。
這是我的代碼:
@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
}
}
根據異常原因,您必須在主線程上執行segue
DispatchQueue.main.async {
self.performSegue(withIdentifier: "Login", sender: self)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.