import UIKit
///文件下载
class VehicleDownloadFilemanager: NSObject, UIDocumentPickerDelegate {

    /// 创建单例对象
    static let share = VehicleDownloadFilemanager()
    private override init() {}
    
     func downloadFile(fileUrl:String?) {
     
        guard let urlStr = fileUrl, let taskUrl = URL(string: urlStr) else { return }
        debugPrint("文件下载url:\(taskUrl)")
        let request = URLRequest(url: taskUrl)
        let session = URLSession(configuration: .default)
        session.downloadTask(with: request) { [weak self] tempUrl, response, error in
            guard let self = self, let tempUrl = tempUrl, error == nil else {
                debugPrint("文件下载失败")
                UIApplication.shared.topViewController?.view.showErrInfo(at: "文件下载失败")
                
                return
            }
            debugPrint("文件下载完成\(tempUrl)")
            // 下载完成之后会自动删除temp中的文件,把文件移动到document中。
            let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
            debugPrint("文件下载完成 documentsDirectory \(documentsDirectory)")
            // 建议使用的文件名,一般跟服务器端的文件名一致
            let destinationPath = documentsDirectory.appendingPathComponent(response?.suggestedFilename ?? "")
            // 如果存在同名的
            if FileManager.default.fileExists(atPath: destinationPath.path) {
                do {
                    try FileManager.default.removeItem(atPath: destinationPath.path)
                } catch _ {
                    
                }
            }
            debugPrint("文件下载 document下的可保存的url:\(destinationPath)")
            do {
                // 文件移动至document
                try FileManager.default.copyItem(atPath: tempUrl.path, toPath: destinationPath.path)
                // main
                DispatchQueue.main.async {
                    self.saveFileToPhone(url: destinationPath)
                }
            } catch let error {
                debugPrint(error)
//                SWToast.showText(message: "\(error.localizedDescription)")
                UIApplication.shared.topViewController?.view.showErrInfo(at: "\(error.localizedDescription)")
            }
        }.resume()
    }

    func saveFileToPhone(url: URL) {
        
        let picker = UIDocumentPickerViewController(url: url, in: .exportToService)
        picker.delegate = self
        picker.modalPresentationStyle = .formSheet
        UIApplication.shared.topViewController?.present(picker, animated: true)
    }

    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        // 保存成功
//        SWToast.showText(message: "保存成功")
        UIApplication.shared.topViewController?.view.showSuccessInfo(at:"保存成功")
    }

    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
    //        SWToast.showText(message: "PickerWasCancelled")
    }

}

 

posted on 2023-12-29 13:48  懂事长qingzZ  阅读(69)  评论(0编辑  收藏  举报