conversations-classic-ios/ConversationsClassic/AppCore/Files/DownloadManager.swift

49 lines
1.6 KiB
Swift
Raw Normal View History

2024-07-12 11:54:40 +00:00
import Foundation
final class DownloadManager {
2024-07-13 01:29:46 +00:00
static let shared = DownloadManager()
2024-07-12 11:54:40 +00:00
private let urlSession: URLSession
2024-07-13 01:29:46 +00:00
private let downloadQueue = DispatchQueue(label: "com.example.downloadQueue")
private var activeDownloads = Set<URL>()
2024-07-12 11:54:40 +00:00
init() {
let configuration = URLSessionConfiguration.default
urlSession = URLSession(configuration: configuration)
}
2024-07-13 01:29:46 +00:00
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)
2024-07-24 09:01:31 +00:00
guard let tempLocalUrl = tempLocalUrl, error == nil else {
2024-07-13 01:29:46 +00:00
completion(error)
2024-07-24 09:01:31 +00:00
return
}
do {
if FileManager.default.fileExists(atPath: localUrl.path) {
try FileManager.default.removeItem(at: localUrl)
}
let data = try Data(contentsOf: tempLocalUrl)
try data.write(to: localUrl)
completion(nil)
} catch let writeError {
completion(writeError)
2024-07-13 01:29:46 +00:00
}
2024-07-12 11:54:40 +00:00
}
}
2024-07-13 01:29:46 +00:00
task.resume()
2024-07-12 11:54:40 +00:00
}
}
}