在Swift 4的wkwebview中添加pdf下载按钮

Mr *_*ite 6 wkwebview swift4 ios11 xcode9

我已经在xcode 9中使用wkwebiew完成了webview应用程序。在网站上,有一些部分需要下载pdf文件,该pdf文件只能查看,但如何制作可以下载到我们的iphone。可以给我一些提示吗,这是我的代码

class ViewController: UIViewController,WKNavigationDelegate,UIWebViewDelegate {

@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var webView: WKWebView!
@IBOutlet var containerView: UIView? = nil
@IBOutlet weak var backButton: UIButton!
@IBOutlet weak var forwardButton: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

    //webview
    self.view.addSubview(self.activityIndicator)
    self.view.addSubview(self.webView)
    let url:URL = URL(string : "https://www.facebook.com")!
    let urlRequest : URLRequest = URLRequest(url: url)
    webView.load(urlRequest)
    webView.navigationDelegate = self


    //activity indicator
    self.webView.addSubview(self.activityIndicator)
    self.activityIndicator.startAnimating()
    self.webView.navigationDelegate = self
    self.activityIndicator.hidesWhenStopped = true
    self.webView.navigationDelegate=self;


    //refresh
    webView.scrollView.bounces = true
    let refreshControl = UIRefreshControl()
    refreshControl.addTarget(self, action: #selector(ViewController.refreshWebView), for: UIControlEvents.valueChanged)
    webView.scrollView.addSubview(refreshControl)

}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear( animated )

    let url:URL = URL(string : "https://www.facebook.com")!
    let urlRequest : URLRequest = URLRequest(url: url)
    webView.load(urlRequest)
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    activityIndicator.stopAnimating()
}

func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
    activityIndicator.stopAnimating()
}

func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
    activityIndicator.startAnimating()
}

@objc func refreshWebView(sender: UIRefreshControl) {
    print("refersh")
    //
    sender.endRefreshing()
}

//back button
@IBAction func backButtonTapped(_ sender: Any) {
    if webView.canGoBack {
        webView.goBack()
    }
}

@IBAction func forwardButtonTapped(_ sender: Any) {
    if webView.canGoForward {
        webView.goForward()
    }
}

func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
    backButton.isEnabled = webView.canGoBack
    forwardButton.isEnabled = webView.canGoForward
}}
Run Code Online (Sandbox Code Playgroud)

小智 0

找到了这段代码。这可能对你有帮助。不要忘记声明所需的委托类。

override func viewDidLoad() {  
    super.viewDidLoad()  

    webView = WKWebView(frame: yourFrame, configuration: webViewConfiguration)   
    webView.uiDelegate = self  
    webView.navigationDelegate = self  

    view.addSubview(webView)  
    webView.load(URLRequest(url: yourUrlString))    
}    


/*  
 Note: We need the suggestedFilename for download  
 */    
func webView(_ webView: WKWebView,    
             decidePolicyFor navigationResponse: WKNavigationResponse,    
             decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {    
    let url = navigationResponse.response.url    

    let documentUrl = url?.appendingPathComponent(navigationResponse.response.suggestedFilename!)    
    loadAndDisplayDocumentFrom(url: documentUrl!)    
    decisionHandler(.cancel)    

}    

/*  
 Now download the file and store it locally in app's temp folder.   
 */    
private func loadAndDisplayDocumentFrom(url downloadUrl : URL) {  
    let localFileURL = FileManager.default.temporaryDirectory.appendingPathComponent(downloadUrl.lastPathComponent)  

        URLSession.shared.dataTask(with: downloadUrl) { data, response, err in  
            guard let data = data, err == nil else {  
                debugPrint("Error while downloading document from url=\(downloadUrl.absoluteString): \(err.debugDescription)")  
                return  
            }  

            if let httpResponse = response as? HTTPURLResponse {  
                debugPrint("Download http status=\(httpResponse.statusCode)")  
            }  

            // write the downloaded data to a temporary folder  
            do {  
                try data.write(to: localFileURL, options: .atomic)   // atomic option overwrites it if needed  
                debugPrint("Stored document from url=\(downloadUrl.absoluteString) in folder=\(localFileURL.absoluteString)")  

                DispatchQueue.main.async {  
                    // localFileURL  
                    // here is where your file 

                }  
            } catch {  
                debugPrint(error)  
                return  
            }  
        }.resume()  
    }  
}  
Run Code Online (Sandbox Code Playgroud)