|
1 | 1 | import Foundation |
2 | 2 |
|
| 3 | +private let networkSession: URLSession = { |
| 4 | + let sessionConfig = URLSessionConfiguration.default |
| 5 | + sessionConfig.timeoutIntervalForRequest = 15 |
| 6 | + sessionConfig.timeoutIntervalForResource = 20 |
| 7 | + return URLSession(configuration: sessionConfig) |
| 8 | +}() |
| 9 | + |
| 10 | +private let imageCache = NSCache<NSString, UIImage>() |
| 11 | +private let imageFetchQueue = DispatchQueue(label: "arkit.imageFetchQueue") |
| 12 | +private var pendingImageRequests: [String: [(UIImage?) -> Void]] = [:] |
| 13 | + |
| 14 | +func prefetchImagesIfNeeded(_ names: [String], completion: @escaping () -> Void) { |
| 15 | + let urls = names.compactMap { URL(string: $0) }.filter { |
| 16 | + $0.scheme == "http" || $0.scheme == "https" |
| 17 | + } |
| 18 | + |
| 19 | + guard !urls.isEmpty else { |
| 20 | + completion() |
| 21 | + return |
| 22 | + } |
| 23 | + |
| 24 | + let group = DispatchGroup() |
| 25 | + for url in urls { |
| 26 | + if imageCache.object(forKey: url.absoluteString as NSString) != nil { |
| 27 | + continue |
| 28 | + } |
| 29 | + group.enter() |
| 30 | + fetchNetworkImageIfNeeded(url) { _ in |
| 31 | + group.leave() |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + group.notify(queue: .main) { |
| 36 | + completion() |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +func fetchNetworkImageIfNeeded(_ url: URL, completion: @escaping (UIImage?) -> Void) { |
| 41 | + if let cached = imageCache.object(forKey: url.absoluteString as NSString) { |
| 42 | + completion(cached) |
| 43 | + return |
| 44 | + } |
| 45 | + let cacheKey = url.absoluteString |
| 46 | + var shouldStartRequest = false |
| 47 | + imageFetchQueue.sync { |
| 48 | + if pendingImageRequests[cacheKey] != nil { |
| 49 | + pendingImageRequests[cacheKey]?.append(completion) |
| 50 | + } else { |
| 51 | + pendingImageRequests[cacheKey] = [completion] |
| 52 | + shouldStartRequest = true |
| 53 | + } |
| 54 | + } |
| 55 | + if !shouldStartRequest { |
| 56 | + return |
| 57 | + } |
| 58 | + |
| 59 | + var request = URLRequest(url: url) |
| 60 | + request.cachePolicy = .useProtocolCachePolicy |
| 61 | + request.setValue("Mozilla/5.0", forHTTPHeaderField: "User-Agent") |
| 62 | + |
| 63 | + let task = networkSession.dataTask(with: request) { data, response, error in |
| 64 | + if let http = response as? HTTPURLResponse, !(200...299).contains(http.statusCode) { |
| 65 | + let httpURLString = http.url?.absoluteString ?? "" |
| 66 | + debugPrint("getImageByName: network non-2xx status \(http.statusCode) url \(httpURLString)") |
| 67 | + } |
| 68 | + |
| 69 | + if let error = error { |
| 70 | + let nsError = error as NSError |
| 71 | + debugPrint( |
| 72 | + "getImageByName: network load failed for \(url.absoluteString) " + |
| 73 | + "error: \(nsError.localizedDescription) " + |
| 74 | + "domain: \(nsError.domain) code: \(nsError.code) " + |
| 75 | + "userInfo: \(nsError.userInfo)" |
| 76 | + ) |
| 77 | + let completions = imageFetchQueue.sync { pendingImageRequests.removeValue(forKey: cacheKey) } ?? [] |
| 78 | + completions.forEach { $0(nil) } |
| 79 | + return |
| 80 | + } |
| 81 | + |
| 82 | + guard let data = data else { |
| 83 | + debugPrint("getImageByName: network returned no data for \(url.absoluteString)") |
| 84 | + let completions = imageFetchQueue.sync { pendingImageRequests.removeValue(forKey: cacheKey) } ?? [] |
| 85 | + completions.forEach { $0(nil) } |
| 86 | + return |
| 87 | + } |
| 88 | + |
| 89 | + let img = UIImage(data: data) |
| 90 | + if img == nil { |
| 91 | + debugPrint("getImageByName: network data not decodable as image for \(url.absoluteString) (bytes: \(data.count))") |
| 92 | + } else { |
| 93 | + imageCache.setObject(img!, forKey: url.absoluteString as NSString) |
| 94 | + } |
| 95 | + let completions = imageFetchQueue.sync { pendingImageRequests.removeValue(forKey: cacheKey) } ?? [] |
| 96 | + completions.forEach { $0(img) } |
| 97 | + } |
| 98 | + task.resume() |
| 99 | +} |
| 100 | + |
3 | 101 | func getImageByName(_ name: String) -> UIImage? { |
4 | 102 | if let img = UIImage(named: name) { |
5 | 103 | return img |
6 | 104 | } |
7 | 105 | if let path = Bundle.main.path(forResource: SwiftArkitPlugin.registrar!.lookupKey(forAsset: name), ofType: nil) { |
8 | | - return UIImage(named: path) |
| 106 | + let img = UIImage(named: path) |
| 107 | + if img == nil { |
| 108 | + debugPrint("getImageByName: failed to load asset image at path \(path) for \(name)") |
| 109 | + } |
| 110 | + return img |
9 | 111 | } |
10 | 112 | if let url = URL(string: name) { |
11 | | - do { |
12 | | - let data = try Data(contentsOf: url) |
13 | | - return UIImage(data: data) |
14 | | - } catch {} |
| 113 | + if let cached = imageCache.object(forKey: url.absoluteString as NSString) { |
| 114 | + return cached |
| 115 | + } |
| 116 | + debugPrint("getImageByName: network image not prefetched for \(name)") |
| 117 | + return nil |
15 | 118 | } |
16 | 119 | if let base64 = Data(base64Encoded: name, options: .ignoreUnknownCharacters) { |
17 | | - return UIImage(data: base64) |
| 120 | + let img = UIImage(data: base64) |
| 121 | + if img == nil { |
| 122 | + debugPrint("getImageByName: base64 data not decodable as image (bytes: \(base64.count))") |
| 123 | + } |
| 124 | + return img |
18 | 125 | } |
| 126 | + debugPrint("getImageByName: failed to resolve image for \(name)") |
19 | 127 | return nil |
20 | 128 | } |
0 commit comments