Lupo
Lupo

Reputation: 25

Xcode 8 Swift 3 show a pdf file on button press

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?

Upvotes: 1

Views: 3524

Answers (1)

Anand Nimje
Anand Nimje

Reputation: 6251

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

Upvotes: 3

Related Questions