所以是的,谢谢你们,我刚刚将整个代码更改为可编码为正确的 swift 4 哈哈。但控制台上仍然没有显示表格 View : “已下载 下载时出现问题”
final let url = URL(string: "https://newsapi.org/v2/top-headlines?sources=espn&apiKey=ada86a1d56d348a29a7c7501869bac2f")
private var articles = [Article]()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
downloadJson()
tableView.tableFooterView = UIView()
}
func downloadJson(){
guard let downloadURL = url else {return}
URLSession.shared.dataTask(with: downloadURL){data, URLResponse, error in
guard let data = data, error == nil, URLResponse != nil else{
print("something is wrong")
return
}
print("downloaded")
do
{
let decoder = JSONDecoder()
let downloadedArticles = try decoder.decode(Articles.self, from: data)
self.articles = downloadedArticles.articles
DispatchQueue.main.async {
self.tableView.reloadData()
}
}catch {
print("something is wrong when downloaded")
}
}.resume()
}
这是来自文章可编码类
class Articles: Codable {
let articles: [Article]
init(articles: [Article]){
self.articles = articles
}
}
class Article: Codable{
let title: String
let description: String
let author: String
let image: String
init(title: String, description: String, author: String, image: String){
self.title = title
self.description = description
self.author = author
self.image = image
}
}
这是 cellforrowat(我无法发布它,因为我的整个帖子主要是代码。哈哈):
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ArticleCell") as? ArticleCell else {
return UITableViewCell()}
cell.titleLabel.text = "" + articles[indexPath.row].title
cell.descLabel.text = "" + articles[indexPath.row].description
cell.authorLabel.text = "" + articles[indexPath.row].author
if let imageURL = URL(string: articles[indexPath.row].image){
DispatchQueue.global().async {
let data = try? Data(contentsOf: imageURL)
if let data = data {
let image = UIImage(data: data)
DispatchQueue.main.async {
cell.imgView.image = image
}
}
}
}
return cell
}
最佳答案
您应该使用 json 和articlesFromJs 检查调试内容。 可能articleFromJs为空或者JSON格式不正确。
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
和
if let articlesFromJson = json["articles"] as? [[String : >AnyObject]]
还使用 Codable 而不是 JSONSerialization。
关于json - 在 swift 4 中从 json 加载数据的空 tableview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48099314/