iosswiftmemory-managementuiimageimage-caching

How do I release cached images when using UIImage(data:)?


I'm noticing heavy memory usage from my image cache in my collection view and need to understand how to release it. I understand the difference between UIImage(named:) and UIImage(contentsOfFile:). However, I'm using UIImage(data:) and I can't seem to find any documentation on releasing image caches in this instance. Any help appreciated. Here's my code snippet:

if let setImage = cell?.viewWithTag(101) as? UIImageView {
    if let url = URL(string: imageURLs[indexPath.item]) {
        let task = URLSession.shared.dataTask(with: url, completionHandler: { data, _, error in
            guard let data = data, error == nil else {
                print("No data detected: \(Error.self)")
                return
            }
            DispatchQueue.main.async {
                let newImageData = UIImage(data: data)

                self.imageData[indexPath.item] = newImageData!
                setImage.image = self.imageData[indexPath.item] as? UIImage
            }
        })
        task.resume()
        URLSession.shared.finishTasksAndInvalidate()
    }
}

Solution

  • I was under the impression that Firestore auto-caching applied to cloud Storage, but it only applies to cloud Database. Once I implemented local caching with NSCache, my problem was solved.