我已经调用了从viewDidLoad方法本身解析json的函数,但是它在"let task = URLSession.shared之后直接转到resume()。dataTask(with: url!){(数据,响应,错误)in"线。然后调用表视图方法numberOfRowsInSection返回0还有index out of range;cellForRowAt索引路径错误!
override func viewDidLoad() {
super.viewDidLoad()
downloadJSON()
}
func downloadJSON() {
let url = URL(string: "https://newsapi.org/v2/top-headlines?country=us&apiKey=4cf7331ecee44bef80b632fd4c1ba6b3")
let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
if error == nil {
do {
let result = try JSONDecoder().decode(APIResponse.self, from: data!)
self.news = result.articles
self.numberOfRows = result.articles.count
print("Articles: (result.articles.count)")
}
catch {
print("JSON Error")
}
}
DispatchQueue.main.async {
self.newsTableView.reloadData()
}
}.resume()
}
//MARK:- Table View Methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// return news.count! // returns 0
return 20
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! NewsTableViewCell
print(indexPath.row, news.count)
//cell.authorName.text = self.news[indexPath.row].author // (index out of range error)
return cell
}
对api的调用是异步的,所以你的数组最初是空的,当vc出现时,输入20会使表重新加载时崩溃,所以你应该提供你的数据源数组大小
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return news.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! NewsTableViewCell
cell.authorName.text = self.news[indexPath.row].author
return cell
}
像这样声明
var news = [News]() // Don't declare it optional