【问题标题】:Read image from cache for app ios with swift使用 swift 从应用程序 ios 的缓存中读取图像
【发布时间】:2017-09-25 04:32:10
【问题描述】:

我目前正在从我的 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 存储中调用表格单元格视图中的图像,然后为:

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

}

【问题讨论】:

  • 这个库非常适合从 Internet 下载图像(我也将它们与 firebase 一起使用),您可以拥有进度、完成处理程序、占位符图像和出色的缓存加载:github.com/rs/SDWebImage

标签: ios swift image firebase firebase-storage


【解决方案1】:

例如,您可以使用 Kingfisher 实现缓存图像。并且效果更好。 link

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

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

例子:

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

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多