another.im-ios/ConversationsClassic/AppCore/Files/DownloadManager.swift
2024-07-13 18:29:08 +02:00

51 lines
2 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 {
let destinationDirectory = localUrl.deletingLastPathComponent()
if !FileManager.default.fileExists(atPath: destinationDirectory.path) {
try FileManager.default.createDirectory(at: destinationDirectory, withIntermediateDirectories: true, attributes: nil)
}
if FileManager.default.fileExists(atPath: localUrl.path) {
try FileManager.default.removeItem(at: localUrl)
}
try FileManager.default.moveItem(at: tempLocalUrl, to: localUrl)
completion(nil)
} catch let writeError {
completion(writeError)
}
} else {
completion(error)
}
}
}
task.resume()
}
}
}