I want the user to press a button and in the WebView there should open a specific pdf document. I have tried several tutorials but they are all outdated (I think). My code so far:
import UIKit
class ViewController: UIViewController {
@IBAction func show(_ sender: Any) {
let url = NSBundle.mainBundle().URLForResource("file", withExtension: "pdf")
if let url = url {
let webView = UIWebView(frame: self.view.frame)
let urlRequest = NSURLRequest(URL: url)
webView.loadRequest(urlRequest)
view.addSubview(webView)
}
}
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
But NSBundle doesn't exist. It has been renamed to Bundle. But even after applying this fix suggestion there are many many other errors and when I fix them all then still nothing works. So there has to be a difference between Swift 1 (or 2) and Swift 3 in showing a pdf document.
Or do I have missed something?
Try to this code for load local PDF inside webView: -
NSBundle now in Swift 3 version as a Bundle
Swift 3
if let pdf = Bundle.main.url(forResource: "file", withExtension: "pdf", subdirectory: nil, localization: nil) {
let req = NSURLRequest(url: pdf)
let webView = UIWebView(frame: CGRect(x:0,y:0,width:self.view.frame.size.width,height: self.view.frame.size.height-40)) //Adjust view area here
webView.loadRequest(req as URLRequest)
self.view.addSubview(webView)
}