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") } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
2020-12-29 iOS 调用系统粘贴板UIPasteboard
2018-12-29 iOS 学习
2018-12-29 swift - 封装百度地图