将使用Kingfisher下载的图像保存到文档目录

时间:2017-08-29 13:04:21

标签: ios swift kingfisher

我正在使用Kingfisher从一组网址下载图片。

我需要将下载或缓存的图像(实际大小的图像)存储在我的文档目录中。

是否可以这样做?

2 个答案:

答案 0 :(得分:1)

使用以下代码将图像加载到图像视图中。完成处理程序将帮助您在下载图像后执行任何任务。

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")
    }
})
}

答案 1 :(得分:0)

试试这个: -

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")
}