小编典典

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

swift

所以我目前正在尝试显示我在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(code =
EXC-I386_INVOP,subcode = 0x0)

我已经找到了一些有关如何执行此操作的教程,但是它们都已经过时或在Objective-C中。


阅读 300

收藏
2020-07-07

共1个答案

小编典典

干得好:

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

苹果公司建议您不要对本地HTML文件使用.loadRequest,同时不要明确将其扩展到其他数据类型。所以我在上面提供了NSData路由。如果要指定textEncodingName,则可以为“
utf-8”,“ utf-16”等。

编辑:Swift 3

这是Swift 3版本的代码,正如苹果建议的那样,使用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(快速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)
       }
2020-07-07