gpt4 book ai didi

ios - URLSession 和 UI 相关任务

转载 作者:行者123 更新时间:2023-11-28 12:20:23 26 4
gpt4 key购买 nike

我正在尝试通过使用 URLSession 从我的 Web 服务器检索 bool 值来验证登录,并在登录失败时显示警报 Controller 。

func requestLogin() {
let url = URL(string: "http://mywebserver/login.php")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
let postString = "username=\(txtUsername.text!)&password=\(txtPassword.text!)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
guard data != nil else {
self.promptMessage(message: "No data found")
return
}
do {
if let jsonData = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary {
let success = jsonData.value(forKey: "success") as! Bool
if (success) {
self.dismiss(animated: false, completion: { action in
//Move to next VC
})
return
} else {
self.dismiss(animated: false, completion: { action in
self.promptMessage(message: "The username or password that you have entered is incorrect. Please try again.")}
)
return
}
} else {
self.dismiss(animated: false, completion: { action in
self.promptMessage(message: "Error: Could not parse JSON!")
})
}
} catch {
self.dismiss(animated: false, completion: { action in
self.promptMessage(message: "Error: Request failed!")
})
}
})
showOverlayOnTask(message: "Logging in...")
task.resume()
}

func promptMessage(message: String) {
let alert = UIAlertController(title: "Login Failed", message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
}

func showOverlayOnTask(message: String) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50))
loadingIndicator.hidesWhenStopped = true
loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
loadingIndicator.startAnimating();
alert.view.addSubview(loadingIndicator)
self.present(alert, animated: true, completion: nil)
}

我遇到的奇怪问题是我的登录警报 Controller 有时不会关闭。它一直卡住,直到我点击屏幕,然后屏幕将关闭并显示下一个警报 Controller 。这很烦人,我不知道我哪里做错了。

我该如何解决这个问题?

最佳答案

也许问题是您试图在不在主线程上执行的情况下关闭 Controller ,通常 UI 更改/更新应该在主线程上执行。

尝试这个并检查是否有效:

DispatchQueue.main.async {
self.dismiss(animated: false, completion: { action in
self.promptMessage(message: "Error: Could not parse JSON!")
})
}

关于ios - URLSession 和 UI 相关任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45051178/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com