我需要使用UIAlert报告POST请求登录是否失败。登录函数位于由我的控制器调用的类中,但是我无法显示警报。
我在控制台上收到以下消息:
警告:尝试在 其视图不在窗口中 等级
!
在我的loginVC中,我致电
loginWithCompletition
,如果说密码错误,我想从uiviewcontroller的扩展名中显示
customErrorMessageAlert(errorMessage:“错误消息”)
但是我不确定这是否是处理错误的正确方法,并且
在我班上:
class LoginHandler : UIViewController{
...}
我有这种方法:loginWithCompletition
func loginWithCompletition(APIUrlString: String, usernameToUse: String, passwordToUse: String, completion: @escaping (String) -> ()) {
let params = "email=\(usernameToUse)&pass=\(passwordToUse)"
let myUrl = URL(string: APIUrlString)
var request = URLRequest(url: myUrl!)
request.httpMethod = "POST"
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpBody = params.data(using: String.Encoding.utf8, allowLossyConversion: false)
//if all went ok
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response : URLResponse?, error: Error?) in
if let httpResponse = response as? HTTPURLResponse {
print("error \(httpResponse.statusCode)")
let responseCode = httpResponse.statusCode
if responseCode == 401 {
DispatchQueue.main.async {
self.customErrorMessageAlert(errorMessage: "cannot login, wrong mail and password")
}
}
}
//here we already get the response
if error != nil {
print("error! \(String(describing: error))")
customErrorMessageAlert(errorMessage: "error message")
return
}
//if all is ok, convert data to json object
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
// print("parseJSON is: \(parseJSON)")
let accessToken = parseJSON["token"] as? String
// print("token is: \(String(describing: accessToken))")
if let accessToken = accessToken {
completion(accessToken)
} else {
print("accessToken is nil")
return
}
DispatchQueue.main.async {
print("all ok!")
}
} else {
print("parseJSON is empty")
}
} catch {
print("error, cannot complete json serialization")
print("error: \(error.localizedDescription)")
return
}
}
task.resume()
//end
}
我的警报:
func customErrorMessageAlert(errorMessage: String) {
//use this method as default error message and alert
print("Warning! \(errorMessage) in: \(String(describing: self.title ?? self.description))")
let alertController = UIAlertController(title: "Error!", message: errorMessage , preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "Close Alert", style: .default, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}