|
| 1 | +// periphery:ignore:all |
| 2 | +import CocoaLumberjackSwift |
| 3 | +import Foundation |
| 4 | + |
| 5 | +/// Service for handling background downloads using `URLSessionConfiguration.background`. |
| 6 | +/// Follows Apple's guidelines for background downloads with app suspension support. |
| 7 | +public class BackgroundDownloadService: NSObject { |
| 8 | + private var backgroundCompletionHandler: (() -> Void)? |
| 9 | + private var downloadTasks: [String: URLSessionDownloadTask] = [:] |
| 10 | + private var downloadContinuations: [String: CheckedContinuation<URL, Error>] = [:] |
| 11 | + private let fileManager: FileManager |
| 12 | + |
| 13 | + public init(fileManager: FileManager = .default) { |
| 14 | + self.fileManager = fileManager |
| 15 | + super.init() |
| 16 | + } |
| 17 | +} |
| 18 | + |
| 19 | +// MARK: - BackgroundDownloadProtocol |
| 20 | + |
| 21 | +extension BackgroundDownloadService: BackgroundDownloadProtocol { |
| 22 | + public func downloadFile(from url: URL, sessionIdentifier: String, allowCellular: Bool) async throws -> URL { |
| 23 | + try await withCheckedThrowingContinuation { continuation in |
| 24 | + let session = createBackgroundSession(identifier: sessionIdentifier, allowCellular: allowCellular) |
| 25 | + let downloadTask = session.downloadTask(with: url) |
| 26 | + |
| 27 | + // Stores the continuation for later use in delegate methods. |
| 28 | + downloadContinuations[sessionIdentifier] = continuation |
| 29 | + downloadTasks[sessionIdentifier] = downloadTask |
| 30 | + |
| 31 | + downloadTask.resume() |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + public func setBackgroundCompletionHandler(_ completionHandler: @escaping () -> Void) { |
| 36 | + backgroundCompletionHandler = completionHandler |
| 37 | + } |
| 38 | + |
| 39 | + public func cancelDownloads(for sessionIdentifier: String) async { |
| 40 | + if let task = downloadTasks[sessionIdentifier] { |
| 41 | + task.cancel() |
| 42 | + downloadTasks.removeValue(forKey: sessionIdentifier) |
| 43 | + |
| 44 | + // Resumes continuation with cancellation error. |
| 45 | + if let continuation = downloadContinuations.removeValue(forKey: sessionIdentifier) { |
| 46 | + continuation.resume(throwing: BackgroundDownloadError.cancelled) |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + // MARK: - Private Methods |
| 52 | + |
| 53 | + private func createBackgroundSession(identifier: String, allowCellular: Bool) -> URLSession { |
| 54 | + let config = URLSessionConfiguration.background(withIdentifier: identifier) |
| 55 | + |
| 56 | + // Configure for background downloads as per Apple guidelines |
| 57 | + config.sessionSendsLaunchEvents = true |
| 58 | + config.isDiscretionary = false // Don't wait for optimal conditions |
| 59 | + config.allowsCellularAccess = allowCellular |
| 60 | + config.timeoutIntervalForRequest = 30 |
| 61 | + config.timeoutIntervalForResource = 300 // 5 minutes |
| 62 | + |
| 63 | + return URLSession(configuration: config, delegate: self, delegateQueue: nil) |
| 64 | + } |
| 65 | + |
| 66 | + private func handleDownloadCompletion(for sessionIdentifier: String, fileURL: URL?, error: Error?) { |
| 67 | + guard let continuation = downloadContinuations.removeValue(forKey: sessionIdentifier) else { |
| 68 | + return |
| 69 | + } |
| 70 | + |
| 71 | + downloadTasks.removeValue(forKey: sessionIdentifier) |
| 72 | + |
| 73 | + if let error { |
| 74 | + continuation.resume(throwing: BackgroundDownloadError.downloadFailed(error)) |
| 75 | + } else if let fileURL { |
| 76 | + continuation.resume(returning: fileURL) |
| 77 | + } else { |
| 78 | + continuation.resume(throwing: BackgroundDownloadError.fileNotFound) |
| 79 | + } |
| 80 | + } |
| 81 | +} |
| 82 | + |
| 83 | +// MARK: - URLSessionDownloadDelegate |
| 84 | + |
| 85 | +extension BackgroundDownloadService: URLSessionDownloadDelegate { |
| 86 | + public func urlSession(_ session: URLSession, |
| 87 | + downloadTask: URLSessionDownloadTask, |
| 88 | + didFinishDownloadingTo location: URL) { |
| 89 | + // For catalog downloads, reads data directly from temp location to save storage space. |
| 90 | + // This is safe for typical JSON catalog files which are usually < 50MB. |
| 91 | + guard let sessionIdentifier = session.configuration.identifier else { |
| 92 | + DDLogError("🟣 Background download session missing identifier") |
| 93 | + return |
| 94 | + } |
| 95 | + |
| 96 | + do { |
| 97 | + // Move downloaded file to temporary directory to prevent iOS from cleaning it up |
| 98 | + // before parsing completes. The temp location returned by URLSession is cleaned |
| 99 | + // immediately after this delegate method returns, but we need the file to persist |
| 100 | + // until async parsing completes. |
| 101 | + let tempDirectory = fileManager.temporaryDirectory |
| 102 | + let fileName = downloadTask.originalRequest?.url?.lastPathComponent ?? "catalog_\(UUID().uuidString).json" |
| 103 | + let persistentTempURL = tempDirectory.appendingPathComponent(fileName) |
| 104 | + |
| 105 | + // Remove existing file if it exists |
| 106 | + if fileManager.fileExists(atPath: persistentTempURL.path) { |
| 107 | + try fileManager.removeItem(at: persistentTempURL) |
| 108 | + } |
| 109 | + |
| 110 | + // Move the downloaded file to our managed temp location |
| 111 | + try fileManager.moveItem(at: location, to: persistentTempURL) |
| 112 | + |
| 113 | + DDLogInfo("🟣 Background download completed, file moved to: \(persistentTempURL.path)") |
| 114 | + |
| 115 | + handleDownloadCompletion(for: sessionIdentifier, |
| 116 | + fileURL: persistentTempURL, |
| 117 | + error: nil) |
| 118 | + } catch { |
| 119 | + DDLogError("🟣 Failed to move downloaded file: \(error.localizedDescription)") |
| 120 | + handleDownloadCompletion(for: sessionIdentifier, |
| 121 | + fileURL: nil, |
| 122 | + error: error) |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + public func urlSession(_ session: URLSession, |
| 127 | + downloadTask: URLSessionDownloadTask, |
| 128 | + didWriteData bytesWritten: Int64, |
| 129 | + totalBytesWritten: Int64, |
| 130 | + totalBytesExpectedToWrite: Int64) { |
| 131 | + let progress = BackgroundDownloadProgress( |
| 132 | + bytesDownloaded: totalBytesWritten, |
| 133 | + totalBytes: totalBytesExpectedToWrite |
| 134 | + ) |
| 135 | + |
| 136 | + // For now, the download progress is logged. |
| 137 | + // We might want to notify observers to update UI on progress changes. |
| 138 | + if totalBytesExpectedToWrite > 0 { |
| 139 | + let percentComplete = Int(progress.progress * 100) |
| 140 | + DDLogInfo("🟣 Download progress: \(percentComplete)%") |
| 141 | + } |
| 142 | + } |
| 143 | + |
| 144 | + public func urlSession(_ session: URLSession, |
| 145 | + task: URLSessionTask, |
| 146 | + didCompleteWithError error: Error?) { |
| 147 | + guard let sessionIdentifier = session.configuration.identifier else { |
| 148 | + DDLogError("🟣 Background download session missing identifier in error handling") |
| 149 | + return |
| 150 | + } |
| 151 | + |
| 152 | + if let error { |
| 153 | + handleDownloadCompletion(for: sessionIdentifier, |
| 154 | + fileURL: nil, |
| 155 | + error: error) |
| 156 | + } |
| 157 | + } |
| 158 | +} |
| 159 | + |
| 160 | +// MARK: - URLSessionDelegate |
| 161 | + |
| 162 | +extension BackgroundDownloadService: URLSessionDelegate { |
| 163 | + public func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { |
| 164 | + // Executes the background URL session completion handler on the main queue because this method may be called on a secondary queue |
| 165 | + // according to doc: |
| 166 | + // https://developer.apple.com/documentation/foundation/downloading-files-in-the-background#Handle-app-suspension |
| 167 | + DispatchQueue.main.async { [weak self] in |
| 168 | + self?.backgroundCompletionHandler?() |
| 169 | + self?.backgroundCompletionHandler = nil |
| 170 | + } |
| 171 | + } |
| 172 | +} |
0 commit comments