5

I have done webview app using wkwebiew in xcode 9. In the website, there are some part need to download the pdf file, the pdf file can be view only but how to make it can be download to our iphone. can you share some tip to me, this is my code

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
}}
Sanoj Kashyap
  • 5,020
  • 4
  • 49
  • 75
Mr White
  • 89
  • 1
  • 6

1 Answers1

0

Found this piece of code. This Might help you. Don't forget to declare the needed delegate classes.

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()  
    }  
}