所以我目前正试图在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.
解决方法
干得好:
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",localization: nil),data = NSData(contentsOfURL: pdfURL),baseURL = pdfURL.URLByDeletingLastPathComponent { let webView = UIWebView(frame: CGRectMake(20,self.view.frame.size.height-40)) webView.loadData(data,MIMEType: "application/pdf",textEncodingName:"",baseURL: baseURL) self.view.addSubview(webView) }
Apple建议您不要在本地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",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 } } } }