Я рекомендую использовать протокол Decodable
для анализа JSON.
Прежде всего вам не нужен класс, унаследованный от NSObject
, достаточно структуры. Структура статьи использует ключи JSON в качестве свойств:
struct News : Decodable {
let status : String
let articles : [Article]
}
struct Article : Decodable {
let description: String?
let author: String?
let url: URL
let urlToImage: URL?
let publishedAt: Date
}
Затем объявите массив источника данных как необязательный
var articles = [Article]()
Затем проанализируйте JSON
func getData() {
let theURL = URL(string: "https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=••••••••••••••••••••")
let task = URLSession.shared.dataTask(with: theURL!) { (data, response, error) in
if error != nil {
print(error!)
return
} else {
do {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let news = try decoder.decode(News.self, from: data!)
self.articles = news.articles
//Making the data be on the main thread.
DispatchQueue.main.async {
self.myTableView.reloadData()
}
} catch {
print(error)
}
}
}
task.resume()
}
В вашем коде есть другие проблемы :
Вы смешиваете numberOfSections
и numberOfRowsInSection
. В numberOfSections
вернуть 1 или пропустить метод
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
В numberOfRowsInSection
вернуть количество артикулов
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return articles.count
}
В cellForRow
используйте .row
вместо .item
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! ArticleCell
let article = self.articles[indexPath.row]
cell.title.text = article.title
cell.theDesc.text = article.description
cell.author.text = article.author
cell.theImageView.downloadImage(from: article.url)
return cell
}
PS:
Настоятельно не рекомендуется делиться своим реальным ключом API на открытом форуме. Лучший способ - опубликовать JSON и исказить ключ .