gpt4 book ai didi

ios - 从 URL 获取响应时警报显示延迟

转载 作者:行者123 更新时间:2023-11-29 00:49:56 24 4
gpt4 key购买 nike

当用户按下按钮在数据库中插入文本时,我尝试显示警报,一切正常,但是当我收到响应并尝试在警报中显示它时,它不会立即工作,警报会在以下情况下显示:按下按钮后,我按下屏幕上的某处。我需要它在按下按钮后立即出现,如果我打印相同的响应它工作正常,但当我使用警报时它不会。

@IBAction func posting(sender: AnyObject) {


let request = NSMutableURLRequest(URL: NSURL(string: "https://example.com/appapi/test2.php")!)
request.HTTPMethod = "POST"
let postString = "a=\(title.text!)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error inenter code here

if error != nil {
print("error=\(error)")
return
}
let responseString = "\(NSString(data: data!, encoding: NSUTF8StringEncoding)!)"
self.displayR(responseString)


}
task.resume()





}
func displayR(str:String){

var alert = UIAlertController(title: "Description", message: "\(str)" ,preferredStyle: .Alert)


alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in }))

self.presentViewController(alert, animated: true, completion: nil)

}

最佳答案

当您通过请求执行数据任务时,代码在后台线程中执行。任何 UI 更改(在本例中显示警报)都必须在主线程上完成。为此,请在以下代码中调用显示函数:

dispatch_async(dispatch_get_main_queue()) {
//call display function here
}

关于ios - 从 URL 获取响应时警报显示延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38259582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com