![](/img/trans.png)
[英]Cache to store image and retrieve from stored Cache is not working - iOS Swift
[英]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:无法从CACHE”读取图像“),但是却显示了print'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实现缓存图像。 并且效果更好。 链接
使用方法:从存储到数据库项节点添加到图像的链接。 像这样:
然后只需使用它来呈现和缓存图像。
例:
let imageView = UIImageView(frame: frame) // init with frame for example
imageView.kf.setImage(with: <urlForYourImageFromFireBase>) //Using kf for caching images
希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.