用swift从应用程序ioscaching中读取图像

我目前正在从我的firebase存储中读取图像 – 这工作正常。

从存储中读取图像时,我设置了一个caching来读取图像:

// Storage.imageCache.object(forKey: post.imageUrl as NSString) static func getImage(with url: String, completionHandler: @escaping (UIImage) -> ()) { if let image = imageCache.object(forKey: url as NSString) { print("CACHE: Unable to read image from CACHE ") completionHandler(image) } else { let ref = FIRStorage.storage().reference(forURL: url) ref.data(withMaxSize: 2 * 1024 * 1024) { (data, error) in if let error = error { print("STORAGE: Unable to read image from storage \(error)") } else if let data = data { print("STORAGE: Image read from storage") if let image = UIImage(data: data) { // Caches the image Storage.imageCache.setObject(image, forKey: url as NSString) completionHandler(image) } } } } } } 

但它不工作。 它似乎根本不起作用,我没有“print(”CACHE:无法读取CACHE中的图像“)”信息,而是显示在我的控制台上,但打印的内容是“print(”STORAGE: “)”

你知道这可以通过任何机会来实现吗?

非常感谢您的时间!

—编辑 –

我从firebase存储中调用表格单元视图中的图像,然后如下所示:

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = self.feedTableView.dequeueReusableCell(withIdentifier: "MessageCell")! as UITableViewCell let imageView = cell.viewWithTag(1) as! UIImageView let titleLabel = cell.viewWithTag(2) as! UILabel let linkLabel = cell.viewWithTag(3) as! UILabel titleLabel.text = posts[indexPath.row].title titleLabel.numberOfLines = 0 linkLabel.text = posts[indexPath.row].link linkLabel.numberOfLines = 0 Storage.getImage(with: posts[indexPath.row].imageUrl){ postPic in imageView.image = postPic } return cell } 

例如,你可以用Kingfisher实现caching图像。 而且效果更好。 链接

如何使用:将存储链接添加到数据库项目节点。 喜欢这个:

在这里输入图像说明

然后用它来呈现和caching图像。

例:

  let imageView = UIImageView(frame: frame) // init with frame for example imageView.kf.setImage(with: <urlForYourImageFromFireBase>) //Using kf for caching images 

希望能帮助到你