Save image downloaded using Kingfisher to Document Directory

2.9k views Asked by At

I'm using Kingfisher to download images from a set of url's.

I need to store the downloaded or cached image (actual sized image) in my Document Directory.

Is it possible to do this?

3

There are 3 answers

1
Pushpendra On

try this:-

let documentsDirectoryURL = try! FileManager().url(for: 
.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: 
true)
// create a name for your image
let fileURL = 
documentsDirectoryURL.appendingPathComponent("imgName.png")


  if !FileManager.default.fileExists(atPath: fileURL.path) {
   do {
    try UIImagePNGRepresentation(cahedimage!)!.write(to: fileURL)
        print("Image Added Successfully")
    } catch {
        print(error)
    }
   } else {
    print("Image Not Added")
}
0
ak_ninan On

Load the image in to the image view using the following code. The completion handler will help out for doing any tasks after the image got downloaded.

loadImage(fromUrl: URL(string: imageUrl)!, imageView: imgView, fileName: image.png)

func loadImage(fromUrl: URL, imageView: UIImageView, fileName: String) {
imageView.kf.indicatorType = .activity
imageView.kf.setImage(with:fromUrl, placeholder: nil, options: [.transition(.none)], progressBlock: nil, completionHandler: {(result) in
    let documentsDirectoryURL = try! FileManager().url(for:
        .documentDirectory, in: .userDomainMask, appropriateFor: nil, create:
        true)

    let fileURL =
        documentsDirectoryURL.appendingPathComponent(fileName)


    if !FileManager.default.fileExists(atPath: fileURL.path) {
        do {
            try UIImagePNGRepresentation(imageView.image!)!.write(to: fileURL)
            print("Image Added Successfully")
        } catch {
            print(error)
        }
    } else {
        print("Image Not Added")
    }
})
}
3
Kaaaaai On

kingfisher now supports this operation,You can use it like this:

    let downLoader = ImageDownloader.default
    let imageURL = URL(string: "http://xxxx.png")!
        
    downLoader.downloadImage(with: imageURL, completionHandler:  { result in
        switch result {
            case .success(let value):
                ImageCache.default.storeToDisk(value.originalData, forKey: "your cache key")
            case .failure(let error):
                print(error)
            }
    })