ios - 在 Collection View 中缓存图像

标签 ios swift caching nsurlsession

我不知道如何修复某些问题。我目前有一个 iPhone 应用程序,它实际上是 Instagram,但只是水平和分页,用户可以在其中查看 friend 的照片。

现在我创建了一个函数,可以从 firebase 获取图像并将它们放入数组中。现在,这与执行共享 URLSession 配合得很好。我注意到我的应用程序的内存使用率很高,因此我添加了一个 URL 缓存,并设置了它可以达到的大小的限制,现在我想起来实际上有点高。但我仍然获得高内存(171mb),并且仅加载 4 个图像使用量,这使得我看起来没有正确缓存数据。

我仍在学习如何使用 URLSessions 以及缓存,因此如果我设置错误,这也可能会导致问题。网上有人说使用SDWebImage,但实际上,用户不会向下滚动或无法快速向下滚动,因为启用了第一个分页并且它是水平的。这是我的一些代码,请告诉我你认为我应该做什么。

 urlcache in 
viewDidLoad() { //probably too high..
  let memoryCapacity = 500 * 1024 * 1024
    let diskCapacity = 500 * 1024 * 1024
    let urlCache = URLCache(memoryCapacity: memoryCapacity,     diskCapacity: diskCapacity, diskPath: "myDiskPath")
    URLCache.shared = urlCache
 }
 // cellforrow
if posts.count != nil  {
         let pozt = posts[indexPath.row].pathToImage
        let url = URL(string: pozt!)
        URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
            if error != nil {
                print(error?.localizedDescription as Any)
                return
            }
            DispatchQueue.main.async {
                cell.myImage.image = UIImage(data: data!)
                self.loader.stopAnimating()
            }
        }).resume()
    }
    cell.myImage.image = UIImage(named: imaqes[0])
  return cell
 }

最佳答案

我认为几乎所有程序员都使用库来缓存图像。 我使用 KingFisher 而不是 SDWebImage。它重量轻且易于使用。

安装:

Podfile:

pod 'Kingfisher'

在终端中:

pod install

在 swift 文件中:

import Kingfisher

在您的情况下,请使用以下方式:

// cellforrow
if posts.count != nil  {
    let pozt = posts[indexPath.row].pathToImage
    let url = URL(string: pozt!)

    DispatchQueue.main.async {
        cell.myImage.kf.setImage(with: url!) //Using kf for caching images
    }
}

return cell

也许您应该将 .kf.setImage 与完成处理程序一起使用来删除加载程序。你应该明白了。

希望对你有帮助

关于ios - 在 Collection View 中缓存图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43927105/

相关文章:

iphone - 如何通过从 UIViewController 向右或向左滑动来更改 UIImageView 中的图像

ios - 隐藏 View 不起作用 - swift

ios - 如何最好地删除所有 UIViewcontroller 并转到单个 UIViewController?

html - Swift 3 NSURL html 错误不编译

ios - 后台抓取,测试问题

ios - CABasicAnimation 如何获取当前的旋转角度

ios - VS Cordova 中的 iOS 部署错误

c# - 使用 ImmutableSortedSet<T> 进行线程安全缓存

asp.net - 如何避免 Global.asax 进行 'VaryByCustom' 缓存

ios - 如何在 iOS 上为多个表缓存从服务器加载的图像