首页 > 解决方案 > 显示系统图像(SF 符号)是否使用 Swift 中的网络调用?

问题描述

我正在 ios 中创建一个应用程序,我使用 UITableView 和 UITableViewCell 从 api 加载图像。

由于 UITableView 重用单元格,所以当我快速滚动时会出现旧图像。为了防止这种情况,我使用系统图像(SF 符号)设置了默认图像。

我还使用缓存来存储图片的网址。

一切正常,但现在我想到了,我每次都发送一个网络请求来检索那个 systemImage,这似乎非常低效,因为我首先使用缓存来减少网络调用的总数。

有没有办法解决这个问题,或者这是我必须做出的权衡?

代码如下。

        //use default image from SF symbols
        let defaulticon = UIImage(systemName: "photo")?.withTintColor(.gray, renderingMode: .alwaysOriginal)
        DispatchQueue.main.async {
            cell.mealImage.image = defaulticon
        }
        
        
        guard cell.meal?.strMealThumb != nil else {
            print("Category Image doesn't exist")
            return
        }
        
        
        //use cache
        if let imageData = model.imagecache.object(forKey: cell.meal!.strMealThumb as NSString) {
            print("using cache")
            DispatchQueue.main.async {
                cell.mealImage.image = imageData
            }
            
        }
        
        else {
            let url = URL(string: cell.meal!.strMealThumb)
            
            let session = URLSession.shared.dataTask(with: url!) { data, response, error in
                
                if error == nil && data != nil {
                    
                    let image = UIImage(data: data!)
                    //self.model.imagecache[cell.meal!.strMealThumb] = image
                    self.model.imagecache.setObject(image!, forKey: cell.meal!.strMealThumb as NSString)
                    DispatchQueue.main.async {
                        cell.mealImage.image = image
                    }
            
                }
            }
            
            session.resume()
            
        }
        

    }

标签: iosswiftapicachinguikit

解决方案


覆盖prepareForReuse方法UITableViewCell并在此函数中添加代码以清除可能因先前使用单元格而持续存在的单相数据。在您的示例中,在此函数中分配默认图像以产生更好的结果。


推荐阅读