Commit 4234268fe5
Unsigned
Layout: unified · split
App/Sources/RemoteImage.swift +41 −4
| @@ -5,21 +5,44 @@ import UIKit | |||
| 5 | /// Images from the network, decoded at the size they are shown rather than full size, and kept in memory. | 5 | /// Images from the network, decoded at the size they are shown rather than full size, and kept in memory. |
| 6 | /// Downloads go through URLSession.shared, so the disk cache set up in `configureURLCache` applies. | 6 | /// Downloads go through URLSession.shared, so the disk cache set up in `configureURLCache` applies. |
| 7 | enum ImageLoader { | 7 | enum ImageLoader { |
| 8 | // NSCache is thread-safe. | 8 | // NSCache is thread-safe. The Library front page alone is about 90 MB of thumbnails, so the limit holds it, |
| 9 | // the news list and a few searches; NSCache gives memory back under pressure. | ||
| 9 | nonisolated(unsafe) private static let cache: NSCache<NSString, UIImage> = { | 10 | nonisolated(unsafe) private static let cache: NSCache<NSString, UIImage> = { |
| 10 | let c = NSCache<NSString, UIImage>() | 11 | let c = NSCache<NSString, UIImage>() |
| 11 | c.totalCostLimit = 60 * 1024 * 1024 | 12 | c.totalCostLimit = 150 * 1024 * 1024 |
| 12 | return c | 13 | return c |
| 13 | }() | 14 | }() |
| 14 | 15 | ||
| 16 | // Two decodes at a time; a list otherwise starts one per row at once. | ||
| 17 | nonisolated(unsafe) private static let decodes: OperationQueue = { | ||
| 18 | let q = OperationQueue() | ||
| 19 | q.maxConcurrentOperationCount = 2 | ||
| 20 | q.qualityOfService = .userInitiated | ||
| 21 | return q | ||
| 22 | }() | ||
| 23 | |||
| 24 | /// Bodies over this size are never stored by URLCache (5% of its disk size). | ||
| 25 | private static let largeBody: Int64 = 20 * 1024 * 1024 | ||
| 26 | |||
| 15 | static func cached(_ url: URL, maxPixels: Int) -> UIImage? { | 27 | static func cached(_ url: URL, maxPixels: Int) -> UIImage? { |
| 16 | cache.object(forKey: key(url, maxPixels)) | 28 | cache.object(forKey: key(url, maxPixels)) |
| 17 | } | 29 | } |
| 18 | 30 | ||
| 19 | static func load(_ url: URL, maxPixels: Int) async throws -> UIImage { | 31 | static func load(_ url: URL, maxPixels: Int) async throws -> UIImage { |
| 20 | if let hit = cached(url, maxPixels: maxPixels) { return hit } | 32 | if let hit = cached(url, maxPixels: maxPixels) { return hit } |
| 21 | let (data, _) = try await URLSession.shared.data(from: url) | 33 | let data: Data |
| 22 | let image = try await Task.detached(priority: .userInitiated) { try downsample(data, maxPixels: maxPixels) }.value | 34 | do { |
| 35 | data = try await URLSession.shared.data(for: URLRequest(url: url), delegate: CancelLargeBody(limit: largeBody)).0 | ||
| 36 | } catch let error as URLError where error.code == .cancelled && !Task.isCancelled { | ||
| 37 | // A data task holds the whole body in memory, twice while it finishes. Download to a file instead | ||
| 38 | // and map it, so ImageIO reads it from disk. | ||
| 39 | let (file, _) = try await URLSession.shared.download(from: url) | ||
| 40 | data = try Data(contentsOf: file, options: .alwaysMapped) | ||
| 41 | try? FileManager.default.removeItem(at: file) | ||
| 42 | } | ||
| 43 | let image = try await withCheckedThrowingContinuation { c in | ||
| 44 | decodes.addOperation { c.resume(with: Result { try downsample(data, maxPixels: maxPixels) }) } | ||
| 45 | } | ||
| 23 | let cost = Int(image.size.width * image.size.height * image.scale * image.scale * 4) | 46 | let cost = Int(image.size.width * image.size.height * image.scale * image.scale * 4) |
| 24 | cache.setObject(image, forKey: key(url, maxPixels), cost: cost) | 47 | cache.setObject(image, forKey: key(url, maxPixels), cost: cost) |
| 25 | return image | 48 | return image |
| @@ -47,6 +70,20 @@ enum ImageLoader { | |||
| 47 | } | 70 | } |
| 48 | } | 71 | } |
| 49 | 72 | ||
| 73 | /// Cancels a data task as soon as its response announces a body over `limit` bytes. | ||
| 74 | private final class CancelLargeBody: NSObject, URLSessionTaskDelegate, @unchecked Sendable { | ||
| 75 | let limit: Int64 | ||
| 76 | private var observation: NSKeyValueObservation? | ||
| 77 | |||
| 78 | init(limit: Int64) { self.limit = limit } | ||
| 79 | |||
| 80 | func urlSession(_ session: URLSession, didCreateTask task: URLSessionTask) { | ||
| 81 | observation = task.observe(\.countOfBytesExpectedToReceive) { [limit] task, _ in | ||
| 82 | if task.countOfBytesExpectedToReceive > limit { task.cancel() } | ||
| 83 | } | ||
| 84 | } | ||
| 85 | } | ||
| 86 | |||
| 50 | /// A remote image decoded for `points` (the longer side it is drawn at), with a placeholder while loading. | 87 | /// A remote image decoded for `points` (the longer side it is drawn at), with a placeholder while loading. |
| 51 | struct RemoteImage<Placeholder: View>: View { | 88 | struct RemoteImage<Placeholder: View>: View { |
| 52 | var url: URL? | 89 | var url: URL? |