// // MP_DownloadManager.swift // MusicPlayer // // Created by 忆海16 on 2024/5/14. // import Foundation import Foundation import Tiercel class DownloadManager: NSObject { static let shared = DownloadManager() var session: SessionManager! var progressHandlers: [URL: (CGFloat) -> Void] = [:] var completionHandlers: [URL: (Result) -> Void] = [:] var downloadTasks: [URL: URLSessionDownloadTask] = [:] var progressStorage: [URL: CGFloat] = [:] // 新增进度存储 var songHandlers:[URL: MPPositive_SongItemModel] = [:] private override init() { super.init() var configuration = SessionConfiguration() configuration.timeoutIntervalForRequest = 60 configuration.maxConcurrentTasksLimit = 6 configuration.allowsCellularAccess = true session = SessionManager("com.yourApp.backgroundDownload", configuration: configuration) } func downloadVideo(from url: URL, song:MPPositive_SongItemModel, progressHandler: @escaping (CGFloat) -> Void, completion: @escaping (Result) -> Void) { progressHandlers[url] = progressHandler completionHandlers[url] = completion songHandlers[url] = song let downloadTask = session.download(url, headers: ["Accept-Encoding": "gzip, deflate"]) //配置进度条 downloadTask?.progress(handler: { [weak self] (task) in guard let self = self else {return} progressHandlers[task.url]?(task.progress.fractionCompleted) progressStorage[task.url] = task.progress.fractionCompleted }) //配置任务完成事件 downloadTask?.success(handler: { [weak self] (task) in guard let self = self else {return} //任务下载成功,进行文件转移 let originalURL = task.url //任务下载地址 let filePathUrl:URL = URL(fileURLWithPath: task.filePath) print("任务下载地址:\(filePathUrl)") let downloadsURL = DocumentsURL.appendingPathComponent("Downloads") if !FileManager.default.fileExists(atPath: downloadsURL.path) { do { try FileManager.default.createDirectory(at: downloadsURL, withIntermediateDirectories: true, attributes: nil) } catch { completionHandlers[originalURL]?(.failure(error)) return } } let fileURL = downloadsURL.appendingPathComponent("\(MP_PlayerManager.shared.loadPlayer.currentVideo.song.videoId ?? "").mp4") do { try FileManager.default.moveItem(at: filePathUrl, to: fileURL) //回调VideoID completionHandlers[originalURL]?(.success(songHandlers[originalURL]!)) progressStorage[originalURL] = nil // 清除已完成任务的进度记录 } catch { completionHandlers[originalURL]?(.failure(error)) } }).failure(handler: { [weak self] (task) in guard let self = self else {return} //任务下载失败 let originalURL = task.url if let error = task.error { completionHandlers[originalURL]?(.failure(error)) } }) } func getProgress(for url: URL) -> CGFloat? { return progressStorage[url] } func cancelAllTasksIfNeeded() { // 根据需求,取消所有任务,或者根据任务状态进行过滤 for key in progressStorage.keys { session.cancel(key) } } //删除下载文件 func deleteFileDocuments(_ videoId:String, completion:@escaping((String) -> Void)) { let downloadsURL = DocumentsURL.appendingPathComponent("Downloads") let fileURL = downloadsURL.appendingPathComponent("\(videoId).mp4") if FileManager.default.fileExists(atPath: fileURL.absoluteString) { do{ try FileManager.default.removeItem(at: fileURL) //文件删除成功 completion(videoId) }catch{ print("删除文件时发生错误:\(error)") } }else { print("文件不存在") } } } //class DownloadManager { // // static let shared = DownloadManager() // // private init() {} // // func downloadVideo(from url: URL, videoId: String, progressView: CircularProgressView, completion: @escaping (Result) -> Void) { // let destination: DownloadRequest.Destination = { _, _ in // let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] // let downloadsURL = documentsURL.appendingPathComponent("Downloads") // // // 检查并创建 Downloads 文件夹 // if !FileManager.default.fileExists(atPath: downloadsURL.path) { // do { // try FileManager.default.createDirectory(at: downloadsURL, withIntermediateDirectories: true, attributes: nil) // } catch { // completion(.failure(error)) // return (downloadsURL, [.removePreviousFile, .createIntermediateDirectories]) // } // } // // let fileURL = downloadsURL.appendingPathComponent("\(videoId).mp4") // return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) // } // // AF.download(url, to: destination).downloadProgress { progress in // progressView.setProgress(to: CGFloat(progress.fractionCompleted)) // }.response { response in // if let error = response.error { // completion(.failure(error)) // } else if let filePath = response.fileURL { // completion(.success(filePath)) // } // } // } //}