Search code examples
sdwebimageloadimage

Is it possible to edit the url of an image before cache it by SDWebImage?


I am using S3 image url. It contains a secret key part. I am using SDWebImage to load the images. I want to cache the images, but due to the signature change from the S3, I am not able to cache the image(due to signature change all image urls are deferent). Is it possible to cache the image without this signature in the url?


Solution

  • I got the answer for this. SDWebImage providing download with out caching and caching with a key. As per my requirement, this is enough.

    • First set the cache key for caching image.
    • Then, check the image is available with that cache key.
    • If not available, then download and cache that image with key.

    Once cached it will be available on the next checking of cache availability. So no need to cache the image multiple times.

    extension UIImageView {

    func setImage(imageUrlString: String) {
        
        let sdManager = SDWebImageManager.shared
        let sdDownloader = SDWebImageDownloader.shared
        let sdChache = SDImageCache.shared
        var cacheKey: String?
        let placeholderimage = UIImage(named: "placeholder.png")
        
        guard let imageURL = URL(string: imageUrlString) else {
            self.image = placeholderimage
            return
        }
        guard let key = sdManager.cacheKey(for: imageURL) else {return}// set the key you want. In the case of s3 images you can remove the signature part and use the remainig url as key, beacause it's unique.
        cacheKey = key
        if let key = cacheKey {
            if let cachedImage = sdChache.imageFromCache(forKey: key) {
                self.image = cachedImage
            }
            else {
                self.sd_imageIndicator = SDWebImageActivityIndicator.gray
                self.sd_imageIndicator?.startAnimatingIndicator()
                sdDownloader.downloadImage(with: imageURL) { (downloadedImage, imageData, error, status) in
                    self.sd_imageIndicator?.stopAnimatingIndicator()
                    if let image = downloadedImage, let data = imageData {
                        self.image = image
                        self.sd_imageIndicator?.stopAnimatingIndicator()
                        sdManager.imageCache.store(image, imageData: data, forKey: key, cacheType: .all) {
                            print("Image Cached with key==> \(key)")
                        }
                    }
                    else{
                        self.image = placeholderimage
                    }
                }
            }
        }
    }
    

    }