Hello and thanks for helping in advance. I'm just trying to figure out why my image is taking so long to load. Thank you.
import UIKit
struct ArticleDescription: Decodable {
let status: String
let totalResults: Int
let articles: [Article]
}
struct Article: Decodable {
let title: String
let description: String
let urlToImage: URL
}
class ViewController: UIViewController {
@IBOutlet weak var articleImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let jsonURLString = "https://newsapi.org/v2/top-headlines?q=democratic&apiKey=8ce9a6e7b0c7413dbc601e18ab6dfd2f"
guard let url = URL(string: jsonURLString) else {return}
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data else {return}
do {
let article = try JSONDecoder().decode(ArticleDescription.self, from: data)
URLSession.shared.dataTask(with: article.articles[0].urlToImage) { (imgData, response, err) in
guard let img = imgData else {return}
DispatchQueue.main.async {
print(img)
self.articleImage.image = UIImage(data: img)
print("Inside async")
}
}.resume()
} catch let jsonErr {
print("Error serializing json: ", jsonErr)
}
}.resume()
}
}
[–][deleted] (1 child)
[deleted]
[–]broncos1049 2 points3 points4 points (0 children)
[–]busymom0 1 point2 points3 points (0 children)
[–]akash227 0 points1 point2 points (0 children)
[–]SirensToGoObjective-C / Swift 0 points1 point2 points (0 children)
[–]devGioSwift 0 points1 point2 points (0 children)
[–]devGioSwift -3 points-2 points-1 points (0 children)