ios 如何在 Swift 中的 UIWebView 中加载本地 PDF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29682245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Load Local PDF in UIWebView in Swift
提问by dannysandler
So I am currently trying to display a local PDF I have in UIWebview and this is the code I'm using:
所以我目前正在尝试显示我在 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);
}
The code will successfully build, but when I run the app, it will crash with the error: Thread 1: EXC_BAD_INSTRUCTION(code=EXC-I386_INVOP,subcode=0x0)
代码将成功构建,但是当我运行应用程序时,它会崩溃并显示错误:线程 1: EXC_BAD_INSTRUCTION(code=EXC-I386_INVOP,subcode=0x0)
I have found a few tutorials on how to do this, but they are all very outdated or in Objective-C.
我找到了一些关于如何做到这一点的教程,但它们都非常过时或在 Objective-C 中。
回答by sketchyTech
Here you go:
干得好:
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)
}
Edit
编辑
The alternative is via NSData:
另一种方法是通过 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 make a point of advising you to not use .loadRequest for local HTML files, while not clearly extending this to other data types. So I've provided the NSData route above. If you wish to specify a textEncodingName it can be "utf-8", "utf-16", etc.
Apple 建议您不要将 .loadRequest 用于本地 HTML 文件,同时没有明确将其扩展到其他数据类型。所以我提供了上面的 NSData 路由。如果您希望指定一个 textEncodingName,它可以是“utf-8”、“utf-16”等。
Edit: Swift 3
编辑:斯威夫特 3
Here's a Swift 3 version of the code using, as Apple advise, WKWebView in place of UIWebView.
这是代码的 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
}
}
}
}
Accessing the PDF from Asset.xcassets (Swift 4)
从 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)
}
回答by iAj
Updated for Swift 3
为 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
}
}
回答by Anil shukla
For Xcode 8.1 and Swift 3.0
对于 Xcode 8.1 和 Swift 3.0
Save the PDF file in any folder of your xcode. Suppose the file name is 'Filename.pdf'
将 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)
}
Same will apply if you want to open any html file.
如果您想打开任何 html 文件,同样适用。
回答by Azharhussain Shaikh
import WebKit
导入 WebKit
here you can load your pdf in your application
在这里您可以在您的应用程序中加载您的 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
}
}
}
回答by AkBombe
For Swift 3use this code:
对于Swift 3,请使用以下代码:
let url = URL(fileURLWithPath: filePath)
let urlRequest = URLRequest(url: url)
webView?.loadRequest(urlRequest)