我正在尝试创建一个带有服务器连接的页面。
一个简单的 POST(电子邮件和密码字段),在响应时,我需要向用户显示一个警报。
这一行导致异常:
self.present(alerta2, animated:true, completion:nil)
这是我的代码:
request.httpMethod = "POST" // Compose a query string
let postString = "email=" + userEmail + "&password=" + userPassword
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil {
self.mostraAlerta(mensagem: "Ocorreu um erro!")
return
}
// Let's convert response sent from a server side script to a NSDictionary object:
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
// print(json)
if let parseJSON = json {
let status = parseJSON["status"] as? String
let msg = parseJSON["msg"] as? String
let titulo = parseJSON["titulo"] as? String
switch status {
case "0"?:
let alerta2 = UIAlertController(title: titulo, message: msg!, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default) { action in
self.dismiss(animated: true, completion: nil)
}
alerta2.addAction(okAction)
self.present(alerta2, animated: true, completion: nil)
// print("Status: OK")
break
case "1"?:
print("Status: " + msg!)
break
default:
print("Status: N/D")
break
}
// print("Status: \(status)")
}
} catch {
print(error)
}
}
task.resume()
异常:
错误:
libsystem_kernel.dylib`__pthread_kill: 0x110b48d38
<+0>: movl $0x2000148, %eax ; imm = 0x2000148 0x110b48d3d
<+5>: movq %rcx, %r10 0x110b48d40
<+8>: syscall -> 0x110b48d42
<+10>: jae 0x110b48d4c ; <+20> 0x110b48d44
<+12>: movq %rax, %rdi 0x110b48d47
<+15>: jmp 0x110b41caf ; cerror_nocancel 0x110b48d4c
<+20>: retq 0x110b48d4d
<+21>: nop 0x110b48d4e
<+22>: nop 0x110b48d4f
<+23>: nop
最佳答案
我刚得到错误和修复。
错误:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIKeyboardTaskQueue waitUntilAllTasksAreFinished] may only be called from the main thread.
解决方法:
OperationQueue.main.addOperation {
self.present(alerta2, animated:true, completion:nil)
}
关于ios - POST 请求后 self.present 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47353003/