表仅显示交互时间,而不是默认情况下

时间:2017-04-18 22:22:27

标签: ios swift tableview

我在视图控制器中有一个表,该表通过字典填充,通过JSON请求从中检索信息。在viewDidLoad()函数中,我调用函数来检索添加到`IncompletedDeadlines字典中的数据:

override func viewDidLoad() {
    super.viewDidLoad()

    self.IncompleteDeadlines = [String:AnyObject]()
    self.retrieveIncompletedDeadlines()
}

一切正常,但表格仅在与之互动时显示。我想也许在视图出现的那一刻显示表格的最好方法是向tableView.reload添加viewDidAppear,如下所示:

override func viewDidAppear(_ animated: Bool) {
    self.tableView.reloadData()
} 

但这并没有解决它。为了清楚起见,我附上了图片。图1显示视图出现的时刻。图2仅在表格与刷卡交互时发生。所以我的问题是如何立即显示表格?我知道由于负载会有延迟,但我不应该与它进行交互以显示:

http://imgur.com/a/0bgTB

当视图与刷卡交互时:

retrieveIncompletedDeadlines()功能如下:

func retrieveIncompletedDeadlines(){
    let myUrl = NSURL(string: "https://www.example.com/scripts/retrieveIncompleteDeadlines.php");
    let request = NSMutableURLRequest(url:myUrl! as URL)
    let user_id = UserDetails[0]
    request.httpMethod = "POST";
    let postString = "user_id=\(user_id)";
    request.httpBody = postString.data(using: String.Encoding.utf8);

    let task = URLSession.shared.dataTask(with: request as URLRequest) {
        data, response, error in

        if error != nil {
            print("error=\(String(describing: error))")
            return
        }

        var err: NSError?
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
            if let parseJSON = json {
                let checker:String = parseJSON["status"] as! String;

                if(checker == "Success"){
                    let resultValue = parseJSON["deadlines"] as! [String:AnyObject]
                    self.IncompleteDeadlines = resultValue
                }
                self.tableView.reloadData()
            }
        } catch let error as NSError {
            err = error
            print(err!);
        }
    }
    task.resume();
    self.tableView.reloadData()
}

1 个答案:

答案 0 :(得分:2)

JSON将在后台线程上解析,但是对UI的任何更新都必须在主线程上完成,因此你必须在const AudioPlayer = { play: function(data) { // Decode the audio data context.decodeAudioData(data, buffer => { // Create a new buffer source source = context.createBufferSource() source.buffer = buffer source.connect(context.destination) // Start playing immediately source.start(context.currentTime) }) }, ... 内完成。article解释了什么是问题。

此外,我会写一个完成处理程序,它在操作完成后返回数据。这是另一个有趣的article

DispatchQueue.main.async {}

Completion handlers are super convenient when your app is doing something that might take a little while, like making an API call, and you need to do something when that task is done, like updating the UI to show the data.