NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

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 = "\(API_KEY)"
        guard let url = URL(string: API_URL)else{
            print("Invalid URL . . . ")
        let request = URLRequest(url: url)
        let decoder = JSONDecoder()
        URLSession.shared.dataTask(with: request) { (data, _, error) in

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

            print(error?.localizedDescription as Any)

    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


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


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.


I used URLSession and Alamofire, same response time.


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


Hacking with Swift is sponsored by Instabug

SPONSORED Catch bugs as soon as they happen and know exactly why a crash occurred. Instabug's SDK grabs all the logs they need to fix bugs, crashes and performance issues in minutes instead of days. Get screenshots, device details, network logs, repro steps, and tons of other critical insights needed to resolve issues and prioritize product backlogs straight from your dashboard. It only takes a minute to integrate!

Get started now

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

Reply to this topic…

You need to create an account or log in to reply.

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.