为什么要使用结构的对话框拨打对话框丢弃此例外?

发布于 2025-01-20 23:34:28 字数 2116 浏览 1 评论 0原文

我试图重定向在结构中解码的 API 调用的输出,但是当我尝试使用数据创建对话框时,它给了我这个奇怪的异常。如您所见,API 返回数据,但仅当我创建对话框时我才会看到此异常。你能帮助我吗?

代码:

struct rspServerInfo: Codable{
        let ok: Bool
        let info: String
    }
    @IBAction func backendDetails(_ sender: Any) {
        
        guard let url = URL(string: "http://\(hostname):\(port)/STOInfo/ServerInfo")else{
            return
        }

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        let body: [String: AnyHashable] = [
            "username": username,
            "password": password,
        
        ]
        
        request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: .fragmentsAllowed)
        let task = URLSession.shared.dataTask(with: request) {data, _, error in
            
            guard let data=data, error == nil else{
                return
            }
            do{
                let response = try JSONDecoder().decode(rspServerInfo.self, from: data)
                print("SUCCESS: \(response)")
                let dialogMessage = UIAlertController(title: "Backend details", message: response.info, preferredStyle: .alert)
                    let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
                         print("Ok button tapped")
                    })
                dialogMessage.addAction(ok)
                self.present(dialogMessage, animated: true, completion: nil)
            }
            catch{
                print(error)
                let dialogMessage = UIAlertController(title: "Backend details", message: "Error retreiving.", preferredStyle: .alert)
                    let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
                         print("Ok button tapped")
                    })
                dialogMessage.addAction(ok)
                self.present(dialogMessage, animated: true, completion: nil)
            }
        }
        task.resume()
    }

I'm trying to redirect the output of this API Call decoded in a struct but when I try to use the data to create a dialog it gives me this weird exception. As you can see, the API returns data but only when I create the dialog I see this exception. Can you help me?

Code:

struct rspServerInfo: Codable{
        let ok: Bool
        let info: String
    }
    @IBAction func backendDetails(_ sender: Any) {
        
        guard let url = URL(string: "http://\(hostname):\(port)/STOInfo/ServerInfo")else{
            return
        }

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        let body: [String: AnyHashable] = [
            "username": username,
            "password": password,
        
        ]
        
        request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: .fragmentsAllowed)
        let task = URLSession.shared.dataTask(with: request) {data, _, error in
            
            guard let data=data, error == nil else{
                return
            }
            do{
                let response = try JSONDecoder().decode(rspServerInfo.self, from: data)
                print("SUCCESS: \(response)")
                let dialogMessage = UIAlertController(title: "Backend details", message: response.info, preferredStyle: .alert)
                    let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
                         print("Ok button tapped")
                    })
                dialogMessage.addAction(ok)
                self.present(dialogMessage, animated: true, completion: nil)
            }
            catch{
                print(error)
                let dialogMessage = UIAlertController(title: "Backend details", message: "Error retreiving.", preferredStyle: .alert)
                    let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
                         print("Ok button tapped")
                    })
                dialogMessage.addAction(ok)
                self.present(dialogMessage, animated: true, completion: nil)
            }
        }
        task.resume()
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

‖放下 2025-01-27 23:34:28

错误消息给出了一个很大的线索:

由于未被发现的例外,终止应用程序
“ nsinternalinconsistencyException”,原因:'对
布局引擎不得从背景线程执行
已从主线程访问。终止于未被发现
类型NSexception

例外

urlrequest在背景线程(包括其完成处理程序)上不同步运行。您(通常)无法在主线程之外进行UI工作。要显示结果,您需要将操作重新推回主线程:

DispatchQueue.main.async {
   // do UI work
}

The error message give a big clue:

Terminating app due to uncaught exception
'NSInternalInconsistencyException', reason: 'Modifications to the
layout engine must not be performed from a background thread after it
has been accessed from the main thread.' terminating with uncaught
exception of type NSException

The URLRequest run asynchronously on a background thread, including its completion handlers. You (generally) can't do UI work outside of the main thread. To display the results you need to push the operation back onto the main thread:

DispatchQueue.main.async {
   // do UI work
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文