因此我的应用程序仅在CollectionView中显示图像,并且由于内存问题而崩溃。这是记忆图
这是您可以检查的示例项目。 ImageTest
我和Kingfisher图书馆和AlamofireImage图书馆一起尝试了同样的项目,两者都崩溃了。
似乎问题可能是由于图像太大造成的。我看到两个解决方案。
尝试使用PINRemoteImage。它在ObjC,但你可以桥接到Swift。此框架允许您设置缓存大小限制,这可以防止内存被吞噬。
但是,这可能没有用,因为您可能最终没有拥有所有图像。
因为,正如您所指出的那样,逐个缩放图像是手动的(因此很繁琐),我建议在客户端进行缩放。
要做到这一点,您可能最终会编写自己的缓存代码。我之前已经这样做了,我可以证明,获得满足您需求的东西实际上非常简单。例如,当我不得不缓存图像时,我最终创建了一个使用url键存储图像的字典。在将图像存储在字典中之前,请将其缩小。
根据要求,这里有一些示例代码可以帮助您。这不是整个代码,但它是一个非常坚实的基础。
下载图像
使用Alamofire
从URL下载图像:
Alamofire.request(.GET, "https://robohash.org/123.png").response { (request, response, data, error) in
self.myImageView.image = UIImage(data: data, scale:1)
}
缩放图像
使用this answer on SO中的代码。您应该缩放到您需要图像的大小,而不是更多。
存储图像
让我们稍微回顾一下。我将所有这些代码由类,ImageManager
或类似的东西管理。
ImageManager
应该:
var delegate: ImageManagerDelegate? // the delegate; more detail below
private(set) var images: [URL: UIImage] = [:] // the cache
func getImage(from url: URL) // the entry point to the class; calls the delegate immediately if the image is already cached, else calls `downloadImage(url: url)`
private func downloadImage(url: URL) // actually downloads the image; calls `cacheImage(url: url, image: downloadedImage)`
private func cacheImage(url: URL, image: UIImage) // caches the image in `images` with `url` as the key, and notifies `delegate` that an image has been cached with the specified url.
ImageManager
也应该实施ImageManagerDelegate
:
protocol ImageManagerDelegate {
func imageManager(_ manager: ImageManager, didGet image: UIImage, from url: URL)
}