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

时间:2015-04-16 17:43:43

标签: ios swift pdf uiwebview

所以我目前正在尝试在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中。

5 个答案:

答案 0 :(得分:45)

你走了:

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"等等。

编辑:Swift 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(Swift 4)访问PDF

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

答案 1 :(得分: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 :(得分: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文件,则同样适用。

答案 3 :(得分: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
           }

      }
 }

答案 4 :(得分:0)

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

let url = URL(fileURLWithPath: filePath)

let urlRequest = URLRequest(url: url)

webView?.loadRequest(urlRequest)