与URLSession和UI相关的任务

时间:2017-07-12 07:31:52

标签: ios swift uialertcontroller

我尝试使用URLSession从我的Web服务器检索布尔值来验证登录,如果登录失败则显示警报控制器。

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)
}

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

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

也许问题是你在没有在主线程上执行的情况下试图解除控制器,通常应该在主线程上执行UI更改/更新。

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

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