Unexpected delays when fetching images from URL in UICollectionView on iOS 16
I'm experiencing significant delays when fetching images from a URL in a UICollectionView on iOS 16. My UICollectionView is displaying thumbnails for a gallery, but the images take several seconds to load, even though the URLs are valid and accessible. I've implemented image fetching using URLSession and caching with NSCache, but I still see noticeable lag when scrolling. Here's a snippet of my image fetching code: ```swift class ImageFetcher { private let imageCache = NSCache<NSString, UIImage>() func fetchImage(from urlString: String, completion: @escaping (UIImage?) -> Void) { if let cachedImage = imageCache.object(forKey: urlString as NSString) { completion(cachedImage) return } guard let url = URL(string: urlString) else { completion(nil) return } URLSession.shared.dataTask(with: url) { data, response, error in if let error = error { print("Error fetching image: \(error.localizedDescription)") completion(nil) return } guard let data = data, let image = UIImage(data: data) else { completion(nil) return } self.imageCache.setObject(image, forKey: urlString as NSString) completion(image) }.resume() } } ``` In my UICollectionViewCell, I'm calling this method like so: ```swift class GalleryCell: UICollectionViewCell { let imageView = UIImageView() let imageFetcher = ImageFetcher() func configure(with urlString: String) { imageFetcher.fetchImage(from: urlString) { [weak self] image in DispatchQueue.main.async { self?.imageView.image = image } } } } ``` Despite this setup, when I scroll quickly, the images sometimes take a second or two to appear, causing a janky scrolling experience. I've tried pre-fetching images in `UICollectionViewDataSourcePrefetching`, but it doesn't seem to resolve the issue. Is there a more efficient way to handle image loading or caching in a UICollectionView on iOS 16? Any suggestions would be greatly appreciated! For context: I'm using Swift on CentOS. Am I approaching this the right way?