UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

I fetched data from API using URLSession in swiftUI, but it takes a long time. How can I cache data?

Forums > SwiftUI

class AriclesViewModel: ObservableObject{

    @Published var articles = [Articles]()

   func fetchData(){
    let API_KEY = ""
    let API_URL = "https://newsapi.org/v2/everything?q=apple&from=2021-04-02&to=2021-04-02&sortBy=popularity&apiKey=\(API_KEY)"
        guard let url = URL(string: API_URL)else{
            print("Invalid URL . . . ")
            return
        }
        let request = URLRequest(url: url)
        let decoder = JSONDecoder()
        URLSession.shared.dataTask(with: request) { (data, _, error) in

            if let data = data{
                do{
                let response = try decoder.decode(News.self, from: data)
                    DispatchQueue.main.async {
                        self.articles = response.articles.compactMap(){$0}
                    }

                   print(response)
                }catch{
                    print(error.localizedDescription)
                }
            }
            print(error?.localizedDescription as Any)
        }.resume()
    }

    var dateFormatter : DateFormatter?{
        let formatter = DateFormatter()
        formatter.dateStyle = .full
        return formatter
    }

    func loadImage(ImageUrl: String) -> Data?{
        guard let url = URL(string: ImageUrl) else {return Data()}
        if let data = try? Data(contentsOf: url){
            return data
        }
        return nil
    }
}

2      

Have you tried the URL in a web browser to see how long the response takes ?

2      

0 dalay in the browser because I hit json file, but when I downlaod images by URLSession and convert it to data to show it inside UIImage, it takes a long time.

2      

I used URLSession and Alamofire, same response time.

2      

More explenations, I want to reuse fetched images in sub-views or anywhere else. In this point , Images take atime to be presented.

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.