Stefano Quarta
Stefano Quarta

Reputation: 67

Async fetching image Firebase Swift 5

I'm using this code in CellForRowAt for showing image. Scrolling is smoothly but network debug says me that it still download image every time that i scroll the table. How can I work for download all the images once?

if let url = URL( string: rest1.image) {
                DispatchQueue.global().async {
                    if let data = try? Data(contentsOf: url) {
                        DispatchQueue.main.async {
                            cell.RestaurantImage.image = UIImage(data: data)
                        }
                    }
                }
            }

Upvotes: 1

Views: 151

Answers (1)

Frankenstein
Frankenstein

Reputation: 16341

You need to use NSCache for saving and retrieving images. Once the images are fetched from network store it inside the Cache and from the next time load the images from the Cache. Create an instance of NSCache with keys NSString and value NSData because NSCache only allows class types. Here's an example:

Create an image cache outside the cellForItem method, or you can create it as Global, like this:

let imageCache = NSCache<NSString, NSData>()

And then in cellForItem method:

if let url = URL(string: rest1.image) {
    if let data = imageCache.object(forKey: rest1.image as NSString) {
        cell.RestaurantImage.image = UIImage(data: data as Data)
    } else {
        DispatchQueue.global().async {
            if let data = try? Data(contentsOf: url) {
                imageCache.setObject(data as NSData, forKey: rest1.image as NSString)
                DispatchQueue.main.async {
                    cell.RestaurantImage.image = UIImage(data: data)
                }
            }
        }
    }
}

Upvotes: 1

Related Questions