簡體   English   中英

快速從應用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:無法從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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM