Music_Player3/MusicPlayer/MP/Common/Tool(工具封装)/MP_DownloadManager.swift
2024-05-20 13:44:14 +08:00

48 lines
1.7 KiB
Swift

//
// MP_DownloadManager.swift
// MusicPlayer
//
// Created by 16 on 2024/5/14.
//
import Foundation
import Foundation
import Alamofire
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))
}
}
}
}