mdmb
mdmb

Reputation: 5283

Firebase - downloading few files

Is there a way to download couple of files (images) using Firebase Storage SDK and live cache those files, so after an image is downloaded the cache is updated?

Can I also observe in another view controller for this cache being updated?

I don't need a whole answer, just maybe a hint where to learn it. I've search through firebase documentation, found some info but I have absolutely no idea how to use it.

Upvotes: 1

Views: 494

Answers (2)

user3296487
user3296487

Reputation: 346

I still haven't found a way to do this from within the Firebase Storage SDK. Here is some code I got off bhlvoong tutorials to cache images using NSCache.

import UIKit

let imageCache = NSCache<AnyObject, AnyObject>()

extension UIImageView {

    func loadImageUsingCacheWithUrlString(urlString: String) {

        self.image = nil

        //check cache for image first
        if let cachedImage = imageCache.object(forKey: urlString as NSString) as? UIImage {
            self.image = cachedImage

            return
        }

        //otherwise fire off a new download
        let url = NSURL(string: urlString)
        URLSession.shared.dataTask(with: url as! URL, completionHandler: { (data, response, error) in

            //download hit an error so lets return out
            if error != nil {
                print(error)

                return
            }

            DispatchQueue.main.async {
                if let downloadedImage = UIImage(data: data!) {
                    imageCache.setObject(downloadedImage, forKey: urlString as NSString)

                    self.image = downloadedImage
                }
            }


        }).resume()
    }


}

Upvotes: 0

Mike McDonald
Mike McDonald

Reputation: 15963

Take a look at NSURLCache. Basically what you'll do is, every time you upload a file to Firebase Storage, you can get a download URL and download it, then storeCachedResponse:forRequest: in the URL cache. Since this cache is shared, you can even grab it across activities.

Similarly, on download, you'll want to check for the cached request via cachedResponseForRequest: and if it doesn't exist, perform the download (at which point you cache the request for later).

Long term, we're hoping to enable this behavior for you out of the box, but for now, you can use NSURLCache to make it happen :)

Upvotes: 3

Related Questions