ios - URLSession 和 UI 相关任务

标签 ios swift uialertcontroller

我正在尝试通过使用 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/

相关文章:

ios - 企业程序在应用程序安装方面有限制吗?

ios - 如何在 UILabel 包含 xml 数据的 UItableview 单元格中显示 UIlabel?

ios - 如何使用 Moya Swift 使用多部分请求上传图像?

ios - 对于 Soap NSURLConnection,请确保您的应用支持 IPv6 网络,因为需要 IPv6 兼容性

ios - Swift iOS - 如何取消 DispatchGroup() 管理循环

ios - 自定义字体在 WatchKit InterfaceFile 中显示自定义(未安装)

ios - 如何引用 UIAlertController 文本框中的输入文本?

ios - 通过索引问题从 sqlite 表中检索数据

swift - 自定义 UIAlertController - 应用程序尝试以模态方式呈现事件 Controller

ios - 如何在我仍然可以看到背景 viewController 的同时呈现 viewController