我正在尝试创建一个带有服务器连接的页面。
一个简单的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&gt ;: movq%rcx,%r10 0x110b48d40
< + 8>:系统调用 - > 0x110b48d42
< + 10>:jae 0x110b48d4c; 1 + 20 - ; 0x110b48d44
< + 12>:movq%rax,%rdi 0x110b48d47
< + 15>:jmp 0x110b41caf; cerror_nocancel 0x110b48d4c
< + 20>:retq 0x110b48d4d
< + 21>:nop 0x110b48d4e
< + 22>:nop 0x110b48d4f
< + 23>:nop
答案 0 :(得分:1)
我刚收到错误和修复。
错误:
***由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:' - [UIKeyboardTaskQueue waitUntilAllTasksAreFinished]只能从主线程中调用。
解决方案:
OperationQueue.main.addOperation {
self.present(alerta2, animated:true, completion:nil)
}