【发布时间】:2018-01-04 16:17:07
【问题描述】:
所以是的,谢谢你们,我刚刚将整个代码更改为可编码为正确的 swift 4 大声笑。但是控制台仍然没有显示tableview 说: “已下载 下载时出现问题”
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
}
【问题讨论】:
-
在某些时候,您需要调试。
article.author = author被调用了吗?当你打电话给self.tableview.reloadData()时,articles是空的吗?