使用 swift 从应用 ios 的缓存中读取图像

Read image from cache for app ios with swift

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

我已经设置了一个缓存,以便在从存储中读取图像时从缓存中读取图像:

    // 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: Unable to read image from CACHE ") ' 显示在我的控制台上,但打印 ' print("STORAGE: Image read from storage") '

请问您知道如何实现吗?

非常感谢您的宝贵时间!

---编辑--

我将来自 firebase 存储的 table 单元格视图中的图像调用为:

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实现图片缓存。并且效果更好。 link

如何使用:将link添加到您的图像从存储到数据库项目节点。像这样:

然后就用它来呈现和缓存图像。

示例:

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

希望对您有所帮助