47 lines
1.6 KiB
Swift
47 lines
1.6 KiB
Swift
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<URL>()
|
|
|
|
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 {
|
|
if FileManager.default.fileExists(atPath: localUrl.path) {
|
|
try FileManager.default.removeItem(at: localUrl)
|
|
}
|
|
try FileManager.default.copyItem(at: tempLocalUrl, to: localUrl)
|
|
completion(nil)
|
|
} catch let writeError {
|
|
completion(writeError)
|
|
}
|
|
} else {
|
|
completion(error)
|
|
}
|
|
}
|
|
}
|
|
task.resume()
|
|
}
|
|
}
|
|
}
|