Swift-下載文件后保存文件到“文件”APP

· 通過(guò)url下載文件
· 得到temp文件后copy至document
· 利用UIDocumentPickerViewController的exportToService,彈出保存文件選項(xiàng)
(UIDocumentPickerViewController的exportToService 在iOS11以后才適用)


    override func rightBarButtonAction(btn: UIButton) {
     
        guard let urlStr = url, 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("文件下載失敗")
                SWToast.showText(message: "文件下載失敗")
                return
            }
            debugPrint("文件下載完成\(tempUrl)")
            // 下載完成之后會(huì)自動(dòng)刪除temp中的文件,把文件移動(dòng)到document中。
            let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
            debugPrint("文件下載完成 documentsDirectory \(documentsDirectory)")
            // 建議使用的文件名,一般跟服務(wù)器端的文件名一致
            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 {
                // 文件移動(dòng)至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)")
            }
        }.resume()
    }
    
    func saveFileToPhone(url: URL) {
        let picker = UIDocumentPickerViewController(url: url, in: .exportToService)
        picker.delegate = self
        picker.modalPresentationStyle = .formSheet
        self.present(picker, animated: true)
    }
    
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        // 保存成功
        SWToast.showText(message: "保存成功")
    }
    
    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
//        SWToast.showText(message: "PickerWasCancelled")
    }

如果接口返回的是流數(shù)據(jù)stream

· 下載后得到Data,data再寫(xiě)入文件

guard let url = URL(string: url) else { return }
        var request = URLRequest(url: url)
        let resultHeaders: [String: String] = ["Authorization": VKLoginManager.authorization ?? "",
                                               "X-Frontend-Tenant-Code": tenantCode]
        request.headers = HTTPHeaders(resultHeaders)
        request.httpMethod = "GET"
        let session = URLSession(configuration: .default)
        
        session.dataTask(with: request) { data, response, error in
            var name = Date().toString(format: "yyyyMMddHHmmss")
            if let res = response as? HTTPURLResponse,
               let disposition = res.allHeaderFields["Content-Disposition"] as? String {
                if disposition.contains(find: "filename=") == true {
                    let pdfList = disposition.components(separatedBy: "filename=")
                    if  let pdfName = pdfList.last {
                        if let fileName = pdfName.components(separatedBy: ".pdf").first {
                            name = fileName.urlDecoded
                        }
                    }
                }
            }
            guard let outputURL = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent(name).appendingPathExtension("pdf")
            else { fatalError("appendingPath失敗") }
            DispatchQueue.main.async {
                do {
                    try data?.write(to: outputURL, options: .atomic)
                    //
                    self.saveFileToPhone(url: outputURL )
                } catch let error {
                    debugPrint(error)
                }
            }
        }.resume()

如圖


exportToService.jpeg
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容