gpt4 book ai didi

ios - 在 Swift 中使用远程 JSON 数据填充 tableView

转载 作者:行者123 更新时间:2023-11-30 12:26:47 26 4
gpt4 key购买 nike

我想用远程 JSON 数据填充 tableView。获取是在 fetchRecentPosts 方法中完成的,并在 viewDidLoad 方法中调用。问题是 dataTaskWithRequest 是异步的, TableView 不等待数据。我读到What is the time delay between getting data and loading to UITableView我应该在dispatch_async中编写self.tableView.reloadData(),但它不起作用。

func fetchRecentPosts(){
let url = XAPI.recentPostURL()
let request = NSURLRequest(URL: url)

let task = session.dataTaskWithRequest(request){
(data, response, error) -> Void in
let result = self.processRecentPostsRequest(data: data, error: error)
allPosts = result
print("session task complete")
}

dispatch_async(dispatch_get_main_queue(),{
self.tableView.reloadData()
})

task.resume()
}

问题是 allPosts 为零,因为 dataTaskWithRequest 尚未完成其任务。

fatal error: unexpectedly found nil while unwrapping an Optional value

override func viewDidLoad() {
super.viewDidLoad()
fetchRecentPosts()
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return allPosts.count
}

最佳答案

你也许可以通过一些小技巧来逃脱。

numberOfRowsInsection 方法中,您可以检查 allPosts.count 的计数,如果为 0(还没有数据),则返回 0,否则返回计数。

然后在 cellForRowAtIndexPath 委托(delegate)中,您可以根据 allPosts 中是否有任何内容相应地调整 View 。

我建议您的单元格使用xib文件,您也许可以有一个LoadingCell.xib和一个PostCell.xib并相应地加载它们。

这样,当您的 View 在设置数据之前加载时,它将显示一条不错的消息,指示数据正在加载。

关于ios - 在 Swift 中使用远程 JSON 数据填充 tableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44093434/

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