关于前端blob协议下载,wkwebview相关适配整理
如果前端使用的blob协议对目标进行下载,该功能是嵌套在iOS客户端中可以这样做:
@available(iOS 14.5, *)func webView(_ webView: WKWebView, navigationAction: WKNavigationAction, didBecome download: WKDownload) {Console.log("didBecomeDownload")download.delegate = self}@available(iOS 14.5, *)func download(_ download: WKDownload, decideDestinationUsing response: URLResponse, suggestedFilename: String, completionHandler: @escaping (URL?) -> Void) {let documentPathch = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!/// 构建你用来存放目标数据的沙箱地址let urlPath = documentPathch + "/" + suggestedFilenameConsole.log("\(urlPath)")/// 这里我选择存放在document目录下,并且使用suggestedFilename来做文件名。保存路径到本地self.documentModel.downlaodLink = urlPath/// 把对应路径传递给block,这样wkwebview就会把下载好的文件存到这个地址completionHandler(URL(fileURLWithPath: urlPath))}@available(iOS 14.5, *)func downloadDidFinish(_ download: WKDownload) {/// 根据你拼接的路径去获取下载的内容/// 如果不需要在应用中管理下载的数据可以保存到,iOS系统自带的文件APP,带上代码方便大家复制黏贴就可以使用let documentPicker = UIDocumentPickerViewController.init(url:URL(fileURLWithPath: path),in: .exportToService)/// 这个代理方法,大家看着来//documentPicker.delegate = selfdocumentPicker.modalPresentationStyle = .formSheetself.present(documentPicker,animated:true)}
把代码块中内容黏贴到,wkwebview中就可以完成对应适配工作。需要引入WKDownloadDelegate。至于业务大家看着来吧 完整链路就是
- func webView(_ webView: WKWebView, navigationAction: WKNavigationAction, didBecome download: WKDownload) 获取前端调度,建立代理
- func download(_ download: WKDownload, decideDestinationUsing response: URLResponse, suggestedFilename: String, completionHandler: @escaping (URL?) -> Void) 构建保存数据的沙箱URL
- func downloadDidFinish(_ download: WKDownload) 下载完成了,根据回调的沙箱URL提取下载好的文件