Problem. I want to parse the json from here and show on a table view, i am using swift 4 and Decodable. but i am getting a type mismatch error. Link to json:
https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=50fb91212a47432d802b3b1ac0f717a3
My Struct looks like this.
struct Root : Decodable {
let status : String
// let totalResults : Int
let articles : [Article]
}
struct Article : Decodable {
let source: Source
let author, title, description: String
let url: URL
// let publishedAt: Date
let urlToImage: String
}
struct Source: Decodable {
let id, name: String
}
My ViewDidLoad Looks like this :
var articles : [Article]? = []
override func viewDidLoad() {
super.viewDidLoad()
tableview.delegate = self
tableview.dataSource = self
fetchArticles()
}
func fetchArticles(){
let jsonURLString = "https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=50fb91212a47432d802b3b1ac0f717a3"
guard let url = URL(string: jsonURLString) else { return }
URLSession.shared.dataTask(with: url) { (data,response,err) in
guard let data = data else { return }
self.myArticles = [Article]()
do{
let decoder = JSONDecoder()
decoder.dataDecodingStrategy = .base64
let root = try decoder.decode(Root.self, from: data)
self.myArticles = root.articles
DispatchQueue.main.async {
self.tableview.reloadData()
}
} catch let error{
print(error)
}
}.resume()
}
My cellForRowAtIndexPath
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCell(withIdentifier: "articleCell", for: indexPath) as! ArticleCell
let article = self.myArticles[indexPath.row]
myCell.title.text = article.title
myCell.body.text = article.description
myCell.author.text = article.author
myCell.imgView.downloadImage(from: ("https://tctechcrunch2011.files.wordpress.com/2017/04/uber-vs-waymo.png"))
return myCell
}
Error i am getting.
No errors, nothing loads to the table view.