2017-08-29 54 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") 
    } 
}) 
} 
相關問題