从URL获取响应时,警报显示较晚

时间:2016-07-08 05:40:13

标签: ios xcode swift swift2 uialertcontroller

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

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

}

1 个答案:

答案 0 :(得分:1)

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

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