ios - WKWebView将pdf保存到ibooks,从链接保存pdf

标签 ios swift pdf webview wkwebview

我是初级学生,目前正在从事项目,我在 WKWebView 中,并且有打开 pdf 的链接。我可以在 Safari 中打开它,然后在 iBooks 中打开,但我希望它在我的应用程序中执行此操作。是否可以 ?

这是它的外观图片:

我可以在其中选择pdf的图片

description1

想象它将打开什么

description2 我的 webview 类

class WebVC: UIViewController, WKUIDelegate {



var webView: WKWebView!

override func viewDidLoad() {
    super.viewDidLoad()
    let myURL = NSURL(string: "\(savedURL!)")
    let myRequest = URLRequest(url: myURL! as URL)
    webView.load(myRequest)
    webView.allowsBackForwardNavigationGestures = true
    webView.allowsLinkPreview = false
}

override func viewWillAppear(_ animated: Bool) {
    self.navigationController?.toolbar.isHidden = false
}

override func loadView() {
    let webConfiguration = WKWebViewConfiguration()
    webView = WKWebView(frame: CGRect(x: 100, y: 100, width: 110, height: 110), configuration: webConfiguration)
    webView.uiDelegate = self
    view = webView

}

@IBAction func logoutPressed(_ sender: AnyObject) {
    defaults.set(false, forKey: "isLogged")
    defaults.set("EMPTY URL", forKey: "savedURL")
    _ = self.navigationController?.popToRootViewController(animated: true)
}


@IBAction func goBack(_ sender: Any?) {
    if (self.webView.canGoBack) {
        self.webView.goBack()
    }
}

}

最佳答案

  • 在 WebView 中打开 pdf

    //步骤1

    webview.uiDelegate = self
    

    //第 2 步 - 实现委托(delegate)函数(此函数将允许您在 Web View 中打开任何单击的 pdf)

    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
    
         // open in current view
         webView.load(navigationAction.request)
         // don't return a new view to build a popup into (the default behavior).
         return nil;
     }
    
  • 下载

就我而言,一旦我在 webview 中打开 pdf,我就会有下载按钮,用于下载当前打开的 pdf

//第 3 步 - 委托(delegate)函数

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        decisionHandler(WKNavigationActionPolicy.allow)
    }
    //find the mimeTime of the current url opened in webview, If it's pdf, we'll give option to download 
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        
        if let mimeType = navigationResponse.response.mimeType {
            //check if mime exists in our acceptable mimes list
            if self.isMimeTypeConfigured(mimeType) {
                self.mime = mimeType
                self.currentUrl = navigationResponse.response.url
                addDownloadButton()
            }
        }
        decisionHandler(.allow)
    }

//第 4 步 - 创建带有辅助函数的扩展

//=== PDF downloading ===
struct MimeType {
    var type:String
    var fileExtension:String
}
extension DownloadManual {
    //button
    private func addDownloadButton(){
        let btn = UIBarButtonItem(image: UIImage(systemName: "tray.and.arrow.down.fill"), style: .plain, target: nil, action: #selector(downloadTapped))
        self.navigationItem.rightBarButtonItem = btn
    }
    @objc func downloadTapped(){
        self.showActivityIndicator(show: true)
        if let url = currentUrl {
            print("download from: \(url)")
            let filename = getDefaultFileName(forMimeType: self.mime)
            
            downloadData(fromURL: url, fileName: filename) { success, destinationURL in
                if success, let destinationURL = destinationURL {
                    
                    self.showActivityIndicator(show: false)
                    print("download result: \(success), \(destinationURL)")
                    self.fileDownloadedAtURL(url: destinationURL)
                }
            }
        }
    }
    
    //helper funcs
    private func isMimeTypeConfigured(_ mimeType:String) -> Bool {
        for record in self.mimeTypes {
            if mimeType.contains(record.type) {
                return true
            }
        }
        return false
    }
    
    func fileDownloadedAtURL(url: URL) {
        print("downloaded at: \(url)")
        DispatchQueue.main.async {
            let activityVC = UIActivityViewController(activityItems: [url], applicationActivities: nil)
            activityVC.popoverPresentationController?.sourceView = self.view
            activityVC.popoverPresentationController?.sourceRect = self.view.frame
            activityVC.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem
            self.present(activityVC, animated: true, completion: nil)
        }
    }
    private func downloadData(fromURL url:URL,
                              fileName:String,
                              completion:@escaping (Bool, URL?) -> Void) {
        webview.configuration.websiteDataStore.httpCookieStore.getAllCookies() { cookies in
            let session = URLSession.shared
            print("downloading ....")
            session.configuration.httpCookieStorage?.setCookies(cookies, for: url, mainDocumentURL: nil)
            let task = session.downloadTask(with: url) { localURL, urlResponse, error in
                if let localURL = localURL {
                    let destinationURL = self.moveDownloadedFile(url: localURL, fileName: fileName)
                    completion(true, destinationURL)
                }
                else {
                    completion(false, nil)
                }
            }

            task.resume()
        }
    }
    private func getDefaultFileName(forMimeType mimeType:String) -> String {
        for record in self.mimeTypes {
            if mimeType.contains(record.type) {
                return "default." + record.fileExtension
            }
        }
        return "default"
    }
    
    private func moveDownloadedFile(url:URL, fileName:String) -> URL {
        let tempDir = NSTemporaryDirectory()
        let destinationPath = tempDir + fileName
        let destinationURL = URL(fileURLWithPath: destinationPath)
        try? FileManager.default.removeItem(at: destinationURL)
        try? FileManager.default.moveItem(at: url, to: destinationURL)
        return destinationURL
    }

希望这对某人有帮助:)

关于ios - WKWebView将pdf保存到ibooks,从链接保存pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40491077/

相关文章:

ios - 是否有任何可用于星级评定的控件?

swift - 你如何编写一个协议(protocol)来指定 Swift 中算术运算符的存在?

php - 在 IE6 中下载文件得到错误的文件名

ios - cellForRow(在 : indexPath) returns nil Swift3

ios - 逐个迭代格式 % 占位符

ios - 什么时候一个类会有多个指定的初始化程序?

ios - Xcode ViewDidLoad 动画 Swift

swift - 修复 UITableView 滞后问题

java - 将 PDF/A-1b 转换为 PDF/A-2

Java Spring MVC 在浏览器中显示 PDF