alexpaul97
(Alexander )
1
My table view cells aren't showing the date of json files collected from NewsApi.com. Can someone pls help ? Link to project below
GitHub - lexypaul13/Covid-News
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! NewsTableViewCell
cell.authorName.text = articles?[indexPath.row].author
cell.headLine.text = articles?[indexPath.row].title
cell.newsImage.downloadImage(from:(self.articles?[indexPath.item].urlImage ?? "nill"))
if let date = articles?[indexPath.row].publishedAt{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
guard let time = dateFormatter.date(from: date) else { return cell }
let formattedString = dateFormatter.string(from:time)
cell.timePublication.text = formattedString
}
return cell
}
Lantua
2
This looks more like a UIKit question. Someone may come by and help, but you'd have better luck asking over Apple Developer Forums since UIKit is an Apple's private framework.
On a side note:
Did you step through the code (with the debugger)? It might help you realize what's going on. Especially if the code doesn't execute something you'd expect.
alexpaul97
(Alexander )
3
I did and theres a nil value
Lantua
4
Try to check the values too, the publishedAt string looks like this: "2020-08-22T18:55:36Z"
If you separate the logic out:
import Foundation
let string = "2020-08-22T18:55:36Z"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
if let time = dateFormatter.date(from: string) {
}
You'd realize that the dateFormat doesn't match the string (try it in playground). You'd actually use "yyyy-MM-dd'T'HH:mm:ss'Z'" to read from the string, the use another formatter to convert it back to string (or just change the dateFormat).
let string = "2020-08-22T18:55:36Z"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
if let date = dateFormatter.date(from: string) {
dateFormatter.dateFormat = "yyyy-MM-dd"
let newString = dateFormatter.string(from: date)
print(newString)
}
PS
I'd suggest that you use JSONDecoder instead of JSONSerialization.
1 Like
alexpaul97
(Alexander )
5
Thanks for the suggestion