This question asked sometimes back,
But if someone looking for swift solution with WKWebView to download .pdf or any file on File manager, this is how I ended-up
class WebPortalVC: UIViewController, WKNavigationDelegate,WKUIDelegate, UIDocumentInteractionControllerDelegate,URLSessionDownloadDelegate {
override following function, that will intercept url, in our case we check ulr ending with .pdf and .csv and redirect to open with file manger view. which enable view file, download and save on device storage, airdrop or share with other apps
just add following functions and check.
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if let url = navigationAction.request.url {
print("fileDownload: check :: (url)")
let extention = "(url)".suffix(4)
if extention == ".pdf" || extention == ".csv"{
print("fileDownload: redirect to download events. (extention)")
DispatchQueue.main.async {
self.downloadPDF(tempUrl: "(url)")
}
decisionHandler(.cancel)
return
}
}
decisionHandler(.allow)
}
func downloadPDF(tempUrl:String){
print("fileDownload: downloadPDF")
guard let url = URL(string: tempUrl) else { return }
let urlSession = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue())
let downloadTask = urlSession.downloadTask(with: url)
downloadTask.resume()
//showHUD(isShowBackground: true); //show progress if you need
}
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
print("fileDownload: documentInteractionControllerViewControllerForPreview")
return self
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
// create destination URL with the original pdf name
print("fileDownload: urlSession")
guard let url = downloadTask.originalRequest?.url else { return }
print("fileDownload: urlSession (url)")
let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let destinationURL = documentsPath.appendingPathComponent(url.lastPathComponent)
// delete original copy
try? FileManager.default.removeItem(at: destinationURL)
// copy from temp to Document
do {
try FileManager.default.copyItem(at: location, to: destinationURL)
myViewDocumentsmethod(PdfUrl:destinationURL)
print("fileDownload: downloadLocation", destinationURL)
DispatchQueue.main.async {
NBMaterialToast.showWithText(self.view, text: "Download Completed", duration: NBLunchDuration.long)
}
} catch let error {
print("fileDownload: error (error.localizedDescription)")
}
// dismissHUD(isAnimated: false); //dismiss progress
}
func myViewDocumentsmethod(PdfUrl:URL){
print("fileDownload: myViewDocumentsmethod (PdfUrl)")
DispatchQueue.main.async {
let controladorDoc = UIDocumentInteractionController(url: PdfUrl)
controladorDoc.delegate = self
controladorDoc.presentPreview(animated: true)
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…