【问题标题】:SDWebImage Download Image Completion Block not being calledSDWebImage 下载图像完成块未被调用
【发布时间】:2018-05-10 07:26:19
【问题描述】:

所以SDWebImage Download image and store to cache for key 这正是我想要在我的应用程序中做的事情。我想将图像存储在密钥中并稍后获取图像。这是我的代码块:

SDWebImageManager.shared().imageDownloader?.downloadImage(with: URL.init(string: url), options: SDWebImageDownloaderOptions.highPriority, progress: { (receivedSize:Int,expectedSize:Int,url : URL?) in
  print("progressing here in this block ")
}, completed: ({(image : UIImage, data : Data,error : Error, finished : Bool)  in
  print("reached in the completion block ")

  if finished {
    SDImageCache.shared().store(image, forKey: "d", toDisk: true, completion: nil)
  } else {
    print(error.localizedDescription)
    showAlert(viewController: self, title: "", message: error.localizedDescription)
  }           
} as? SDWebImageDownloaderCompletedBlock))

但是,完成块永远不会被调用。

【问题讨论】:

  • print("progressing here in this block") : 这是打印出来的?
  • 是的,它到达了进度块,但没有到达完成块
  • 有什么解决办法吗?

标签: ios swift image caching sdwebimage


【解决方案1】:

使用这段代码:

SDWebImageManager.shared().loadImage(with: NSURL.init(string: individualCellData["cover_image"] as! String ) as URL?, options: .continueInBackground, progress: { (recieved, expected, nil) in
            print(recieved,expected)
        }, completed: { (downloadedImage, data, error, SDImageCacheType, true, imageUrlString) in
            DispatchQueue.main.async {
                if downloadedImage != nil{
                    self.yourImageView.image = downloadedImage
                }
            }
        })

而且您不必再次缓存图像,因为 SDWebImage 已经在执行此操作。要从缓存中检索图像,只需在此代码中使用相同的 url,如果它存在,它将从缓存中获取图像。

更新代码:

如果您想使用自己的密钥,请使用 imageDownloader 而不是 loadImage :

SDWebImageManager.shared().imageDownloader?.downloadImage(with: NSURL.init(string: individualCellData["cover_image"] as! String ) as URL?, options: .continueInBackground, progress: { (recieved, expected, nil) in
                print(recieved,expected)
            }, completed: { (image, data, error, true) in
                print("Completed")
            })

print("Completed") 之后如果没有错误,请使用您的缓存代码使用您的自定义密钥缓存图像。

【讨论】:

  • 我不必将其存储到密钥中,然后稍后再检索吗?就像我的应用程序中的某些情况一样,某个标记被附加到 url,即使图像的 url 保持不变,标记每次都会变化。因此,我只需要在这种情况下更新密钥。有什么想法吗?
  • 检查更新的代码。完成块中存在差异。
  • @DilipTiwari 您可以使用其中任何一个。但我建议第一个。
  • @SharadChauhan 如果我先使用它会做什么,因为我正在使用 sdwebimage 你能解释更多以加载更快的图像
  • @DilipTiwari 两者都是相同的,首先您不需要手动缓存图像,SDWebImage 会为您完成,并且该缓存图像的键将是该图像的 URL。但是,如果您想编写自己的逻辑来使用自定义键缓存图像,请使用第二个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-15
  • 1970-01-01
相关资源
最近更新 更多