Music_Player3/MusicPlayer/MP/Common/Tool(工具封装)/MP_DownloadManager.swift
2024-05-29 17:31:45 +08:00

142 lines
5.8 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// 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<MPPositive_SongItemModel, Error>) -> 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<MPPositive_SongItemModel, Error>) -> 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<URL, Error>) -> 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))
// }
// }
// }
//}