Muju
Muju

Reputation: 979

How to open pdf file in swift directly from URL

I am new in swift and I am unable to open pdf file from url

my code is like this

 @IBOutlet var webview: WKWebView!


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        webview.navigationDelegate = self

        let url = URL(string: "http://www.orimi.com/pdf-test.pdf")
        self.webview.load(URLRequest(url: url!))

    }

    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        print("Start loading")
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("End loading")
    }

I am using this code I am able to open url link and image but not able to open pdf file

Upvotes: 1

Views: 10442

Answers (5)

Shehzad Ali
Shehzad Ali

Reputation: 168

If you want to load your pdf file in WKWebView, you can use the following code:-

import UIKit
import WebKit

class WebViewController: UIViewController {

    @IBOutlet weak var webView: WKWebView! {
        didSet {
            webView.navigationDelegate = self
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        loadWebView()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(true)
        hideLoader()
    }

    private func loadWebView() {
        showLoader()
        let request = URLRequest(url: URL(string: "http://www.orimi.com/pdf-test.pdf)!)
        DispatchQueue.main.async {
            self.webView.load(request)
        }
    }

    private func showLoader() {
        DispatchQueue.main.async {
            //show your loader
        }
    }

    private func hideLoader() {
        DispatchQueue.main.async {
            //hide your loader
        }
    }

}

extension WebViewController: WKNavigationDelegate {

    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        hideLoader()
        showAlert(error.localizedDescription)
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        hideLoader()
    }

}

Upvotes: 0

Christian
Christian

Reputation: 4641

You are trying to load a http-Url into a WebView which is prohibited by default in iOS. You can try the same code with an https-Url or change your Transport Security Settings in the Info.plist to allow Arbitrary loads

Another useful idea might be to use SFSafariViewController to show a website or document from another url.

Upvotes: 1

Kenan Begić
Kenan Begić

Reputation: 1228

Why do you use WKWebView because you can use most common approach, and that is using UIDocumentInteractionController and UIAlertController

Check this part of code that is using popular Alamofire with progressview (you can use any library that you like for similar functionality and also URLSession of course).

Note if you are using this in your controller, it must implement delegate UIDocumentInteractionControllerDelegate.

Here is the full source code with download function and progressbar:

class MyController: UIViewController, UIDocumentInteractionControllerDelegate {

        var progressView: UIProgressView?    

        override func viewDidLoad() {
            super.viewDidLoad()
        }               

        func downloadCommentFile(id: Int) {
            let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)  

            //MARK: Progress controller
            let alertView = UIAlertController(title: "Downloading", message: "Downloading file", preferredStyle: .alert)
            alertView.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

            //  Show UIAlertController it to your users
            present(alertView, animated: true, completion: {
                //  Add your progressbar after alert is shown (and measured)
                let margin:CGFloat = 8.0
                let rect = CGRect(x: margin, y: 72.0, width: alertView.view.frame.width - margin * 2.0 , height: 10.0)
                self.progressView = UIProgressView(frame: rect)
                self.progressView!.progress = 0
                self.progressView!.tintColor = self.view.tintColor
                alertView.view.addSubview(self.progressView!)
            })

            let url = "http://MyUrl/DownloadFile"
            let headers = ["Header1": "header 1 value"]

            Alamofire.download(url,
                method: .post,
                parameters: ["id": id],
                encoding: JSONEncoding.default,
                headers: headers,
                to: destination).downloadProgress(closure: { (progress) in
                    //progress closure                  
                    self.progressView?.setProgress(Float(progress.fractionCompleted), animated: true)
                }).response(completionHandler: { (DefaultDownloadResponse) in
                    //here you able to access the DefaultDownloadResponse
                    //result closure
                    alertView.dismiss(animated: true, completion: {
                        let viewer = UIDocumentInteractionController(url: DefaultDownloadResponse.destinationURL!)
                        viewer.delegate = self
                        viewer.presentPreview(animated: true)
                })
            })      
        }

        func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
            return self
        }

        private func documentInteractionControllerViewForPreview(controller: UIDocumentInteractionController!) -> UIView! {
            return self.view
        }

        func documentInteractionControllerRectForPreview(_ controller: UIDocumentInteractionController) -> CGRect {
            return self.view.frame
        }
    }

Upvotes: 0

Ruben Nahatakyan
Ruben Nahatakyan

Reputation: 408

If you use >= iOS 11 you can use Apples PDFKit. Here example.

import PDFKit


class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let pdfView = PDFView(frame: view.bounds)
        view.addSubview(pdfView)

        if let url = URL(string: link_of_pdf), let document = PDFDocument(url: url) {
            pdfView.document = document
        }
    }
}

But if you need support for less than iOS 11, you can use CGPDFDocument(but you need to work a lot with this), or find third party lib.

Upvotes: 3

Darshan
Darshan

Reputation: 2379

try this below code and let me know

 @IBOutlet weak var webView: WKWebView!


override func viewWillAppear(_ animated: Bool) {

        super.viewWillAppear(true)
        self.initialSetup()
    }

    private func initialSetup () {
        webView.navigationDelegate = self
        self.loadHTMLStringImage()

    }

    private func loadHTMLStringImage() -> Void {
            let htmlString = "<p>Identify the arrow-marked structures in the imagesIdentify the arrow-marked structures in the imagesIdentify the arrow-marked structures in the imagesIdentify the arrow-marked structures in the imagesIdentify the arrow-marked structures in the imagesIdentify the arrow-marked structures in the imagesIdentify the arrow-marked structures in the imagesIdentify the arrow-marked structures in the imagesIdentify the arrow-marked structures in the imagesIdentify the arrow-marked structures in the imagesIdentify the arrow-marked structures in the imagesIdentify the arrow-marked structures in the imagesIdentify the arrow-marked structures in the imagesIdentify the arrow-marked structures in the imagesIdentify the arrow-marked structures in the imagesIdentify the arrow-marked structures in the imagesIdentify the arrow-marked structures in the imagesIdentify the arrow-marked structures in the imagesIdentify the arrow-marked structures in the imagesIdentify the arrow-marked structures in the imagesIdentify the arrow-marked structures in the images</p>"
            webView.loadHTMLString(htmlString, baseURL: nil)
        }

Upvotes: 0

Related Questions