【问题标题】:Save image downloaded using Kingfisher to Document Directory将使用 Kingfisher 下载的图像保存到文档目录
【发布时间】:2017-08-29 13:04:20
【问题描述】:

我正在使用 Kingfisher 从一组 url 下载图像。

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

可以这样做吗?

【问题讨论】:

  • 是的,这是可能的,到目前为止您尝试过什么?什么不工作?
  • 我已经通过使用带有 kf.setImage() 的完成处理程序来完成它

标签: ios swift kingfisher


【解决方案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")
    }
})
}

【讨论】:

    【解决方案2】:

    翠鸟现在支持这个操作,你可以这样使用:

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

    【讨论】:

    • 如果我使用相同的缓存键,.storeToDisk 会替换现有的图像数据吗?如果是这样,这就是我需要的。 :)
    • 是的,我已经测试过了,它将替换旧数据。
    • 图像数据会被删除吗?
    【解决方案3】:

    试试这个:-

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

    【讨论】:

    • 此代码保存到文档目录。我的问题不是那个。
    猜你喜欢
    • 1970-01-01
    • 2015-12-05
    • 1970-01-01
    • 1970-01-01
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-26
    相关资源
    最近更新 更多