首页 > 解决方案 > 无法让 API 调用及时运行 tableview swift 4 xcode 9

问题描述

我正在尝试获取 API 调用来填充列表视图的单元格,但似乎无法在生成单元格之前获取要收集的数据。我已经尝试过像这里一样制作完成处理程序以及来自同一链接的信号量,但无济于事。编译完成处理程序时,它在执行时仍然没有及时获取数据(诚然,这是我第一次尝试完成处理程序)。这是没有完成处理程序的原始代码:

override func viewDidLoad() {
    super.viewDidLoad()

    RestaurantListView.delegate = self
    RestaurantListView.dataSource = self
    //API setup
    guard let url = URL(string: "https://myURL.com") else {
        print("ERROR: Invalid URL")
        return
    }
    let task = URLSession.shared.dataTask(with: url) {

        (data, response, error) -> Void in

        // URL request is complete
        guard let data = data else {
            print("ERROR: Unable to access content")
            return
        }

        guard let blog = try? JSONDecoder().decode(Blog.self, from: data) else {
            print("Error: Couldn't decode data into Blog")
            return
        }
        self.myData = blog
    }
    task.resume()
}

表格和单元格在这些函数下方初始化:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 100
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = RestaurantListView.dequeueReusableCell(withIdentifier: "cell")
    cell?.textLabel?.text = myAPIValue
    return cell!
    }

我有几个打印语句来跟踪程序,它通过 viewDidLoad 然后第一个 tableView 设置表格然后第二个处理单元格,最后它通过 URL 任务。

我已经重写了几十种不同的方式,但不知道如何让它以正确的顺序执行。

标签: iosswiftuitableviewnsurlsession

解决方案


您需要重新加载表,因为此行URLSession.shared.dataTask(with: url)触发了一个异步任务,该任务与您的代码行的顺序不同

guard let blog = try? JSONDecoder().decode(Blog.self, from: data) else {
     print("Error: Couldn't decode data into Blog")
     return
}
self.myData = blog

DispatchQueue.main.async{
    RestaurantListView.reloadData()
}

推荐阅读