import Foundation final class DownloadManager { static let shared = DownloadManager() private let urlSession: URLSession private let downloadQueue = DispatchQueue(label: "com.example.downloadQueue") private var activeDownloads = Set() init() { let configuration = URLSessionConfiguration.default urlSession = URLSession(configuration: configuration) } func enqueueDownload(from url: URL, to localUrl: URL, completion: @escaping (Error?) -> Void) { downloadQueue.async { if self.activeDownloads.contains(url) { print("Download for this file is already in queue.") return } self.activeDownloads.insert(url) let task = self.urlSession.downloadTask(with: url) { tempLocalUrl, _, error in self.downloadQueue.async { self.activeDownloads.remove(url) if let tempLocalUrl = tempLocalUrl, error == nil { do { try FileManager.default.copyItem(at: tempLocalUrl, to: localUrl) completion(nil) } catch let writeError { completion(writeError) } } else { completion(error) } } } task.resume() } } }