如何在Swift中的UIWebView中加载本地PDF

问题描述 投票:18回答:5

所以我目前正在尝试在UIWebview中显示我有的本地PDF,这是我正在使用的代码:

@IBOutlet weak var webView:UIWebView!
override func viewDidLoad() {
    super.viewDidLoad()    

var pdfLoc = NSURL(fileURLWithPath:NSBundle.mainBundle().pathForResource("Sample", ofType:"pdf")!) 
var request = NSURLRequest(URL: pdfLoc);
self.webView.loadRequest(request);
}

代码将成功构建,但是当我运行应用程序时,它将崩溃并出现错误:线程1:EXC_BAD_INSTRUCTION(代码= EXC-I386_INVOP,子代码= 0x0)

我找到了一些关于如何做到这一点的教程,但它们都已经过时或者在Objective-C中。

ios swift pdf uiwebview
5个回答
47
投票

干得好:

if let pdf = NSBundle.mainBundle().URLForResource("myPDF", withExtension: "pdf", subdirectory: nil, localization: nil)  {
            let req = NSURLRequest(URL: pdf)
            let webView = UIWebView(frame: CGRectMake(20,20,self.view.frame.size.width-40,self.view.frame.size.height-40))
            webView.loadRequest(req)
            self.view.addSubview(webView)
        }

编辑

另一种方法是通过NSData:

if let pdfURL = NSBundle.mainBundle().URLForResource("myPDF", withExtension: "pdf", subdirectory: nil, localization: nil),data = NSData(contentsOfURL: pdfURL), baseURL = pdfURL.URLByDeletingLastPathComponent  {
    let webView = UIWebView(frame: CGRectMake(20,20,self.view.frame.size.width-40,self.view.frame.size.height-40))
    webView.loadData(data, MIMEType: "application/pdf", textEncodingName:"", baseURL: baseURL)
    self.view.addSubview(webView)
}

Apple建议您不要将.loadRequest用于本地HTML文件,而不是明确地将其扩展到其他数据类型。所以我在上面提供了NSData路由。如果你想指定textEncodingName,它可以是“utf-8”,“utf-16”等。

编辑:斯威夫特3

这是Swift 3版本的代码,正如Apple建议的那样,使用WKWebView代替UIWebView。

import UIKit
import WebKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        if let pdfURL = Bundle.main.url(forResource: "myPDF", withExtension: "pdf", subdirectory: nil, localization: nil)  {
            do {
                let data = try Data(contentsOf: pdfURL)
                let webView = WKWebView(frame: CGRect(x:20,y:20,width:view.frame.size.width-40, height:view.frame.size.height-40))
                webView.load(data, mimeType: "application/pdf", characterEncodingName:"", baseURL: pdfURL.deletingLastPathComponent())
               view.addSubview(webView)

            }
            catch {
                // catch errors here
            }

        }
    }

}

从Asset.xcassets访问PDF(Swift 4)

if let asset = NSDataAsset(name: "myPDF") {
            let url = Bundle.main.bundleURL
            let webView = WKWebView(frame: CGRect(x:20,y:20,width:view.frame.size.width-40, height:view.frame.size.height-40))
            webView.load(asset.data, mimeType: "application/pdf", characterEncodingName:"", baseURL:url)
            view.addSubview(webView)
       }

4
投票

针对Swift 3进行了更新

import UIKit
import WebKit

class ViewController: UIViewController {

    let webView = WKWebView()

    override func viewDidLoad() {
        super.viewDidLoad()

        loadPdf()
        setupViews()
    }

    func loadPdf() {

        if let pdfUrl = Bundle.main.url(forResource: "YourPdfFileName", withExtension: "pdf", subdirectory: nil, localization: nil) {

            do {
                let data = try Data(contentsOf: pdfUrl)
                webView.load(data, mimeType: "application/pdf", characterEncodingName:"", baseURL: pdfUrl.deletingLastPathComponent())
                print("pdf file loading...")
            }
            catch {
                print("failed to open pdf")
            }
            return
        }

        print("pdf file doesn't exist")
    }

    func setupViews() {

        title = "View PDF Demo"
        view.backgroundColor = .white
        view.addSubview(webView)

        // setup AutoLayout...
        webView.translatesAutoresizingMaskIntoConstraints = false
        webView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        webView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        webView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        webView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
    }
}

enter image description here


2
投票

对于Xcode 8.1和Swift 3.0

将PDF文件保存在xcode的任何文件夹中。假设文件名是'Filename.pdf'

 if let pdf = Bundle.main.url(forResource: "Filename", withExtension: "pdf", subdirectory: nil, localization: nil)  {
    let req = NSURLRequest(url: pdf)
    webViewPresentation.loadRequest(req as URLRequest)        
  }

如果要打开任何html文件,则同样适用。


1
投票

导入WebKit

在这里,您可以在您的应用程序中加载您的pdf

 override func viewDidLoad() {
      super.viewDidLoad()
      // Do any additional setup after loading the view, typically from a nib.

      if let pdfURL = Bundle.main.url(forResource: "food-and-drink-menu-trafalgar-tavern", withExtension: "pdf", subdirectory: nil, localization: nil)  {
           do {
                let data = try Data(contentsOf: pdfURL)
                let webView = WKWebView(frame: CGRect(x:0,y:NavigationView.frame.size.height,width:view.frame.size.width, height:view.frame.size.height-NavigationView.frame.size.height))
                webView.load(data, mimeType: "application/pdf", characterEncodingName:"", baseURL: pdfURL.deletingLastPathComponent())
                view.addSubview(webView)

           }
           catch {
                // catch errors here
           }

      }
 }

0
投票

对于Swift 3,请使用以下代码:

let url = URL(fileURLWithPath: filePath)

let urlRequest = URLRequest(url: url)

webView?.loadRequest(urlRequest)
© www.soinside.com 2019 - 2024. All rights reserved.