【问题标题】:Alert displaying late while getting response from URL收到来自 URL 的响应时,警报显示延迟
【发布时间】:2016-07-08 05:40:13
【问题描述】:

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

@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)

}

【问题讨论】:

    标签: ios xcode swift swift2 uialertcontroller


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      • 2013-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多