2017-08-29 63 views
0

我使用Kingfisher从一组url下载图像。将使用翠鸟下载的图像保存到文档目录

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

可以做到这一点吗?

+2

是的这是可能的,你到目前为止尝试过什么?什么不工作? – Scriptable

+0

我已经通过使用与kf.setImage() – AKNinan

回答

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

完成处理程序完成此代码将保存到文档目录。我的问题不是这样。 – AKNinan

0

加载图像中使用下面的代码图像视图。完成处理程序将帮助完成下载图像后的任何任务。

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