如何直接从 URL 打开 swift 中的 pdf 文件

How to open pdf file in swift directly from URL

我是 swift 的新手,我无法从 url 打开 pdf 文件

我的代码是这样的

 @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")
    }

我正在使用此代码我可以打开 url link 和图像但无法打开 pdf 文件

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

如果你使用 >= iOS 11 你可以使用 Apples PDFKit。举个例子。

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

但是如果你需要小于iOS 11的支持,你可以使用CGPDFDocument(但是你需要做很多工作),或者找第三方库。

为什么用WKWebView因为你可以用最常用的方法,那就是用UIDocumentInteractionControllerUIAlertController

检查这部分代码使用流行的 Alamofire 和 progressview(您可以使用任何您喜欢的库来实现类似的功能,当然 URLSession)。

请注意,如果您在控制器中使用它,它必须实现委托 UIDocumentInteractionControllerDelegate

这里是完整的源代码,带有下载功能和进度条:

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

您正在尝试将 http-Url 加载到 iOS 默认禁止的 WebView 中。您可以使用 https-Url 尝试相同的代码或更改 Info.plist 中的传输安全设置以允许任意加载

另一个有用的想法可能是使用 SFSafariViewController 显示来自另一个 url 的网站或文档。

如果你想在WKWebView中加载你的pdf文件,你可以使用下面的代码:-

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

}