user1828605 user1828605 - 11 months ago 43
iOS Question

How to display PDF files from remote location on UIWebView using Swift?

I'm trying to display a pdf file, using an iOS app, that is located on our website. Here's how I'm doing this:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
print("preparing segue")
if segue.identifier == "PdfWebView" {

print("Found segue")

let detailViewController = segue.destinationViewController as! PdfViewController

let myIndexPath = self.tableView.indexPathForSelectedRow!

let row = myIndexPath.row


//Pass selected cell title to next View
detailViewController.website = pdfLinks[row]

print("Website: ", detailViewController.website)
}
}


// This is on pdfViewController

// The webiste = http://www.example.com/some-pdf-document-to-display.pdf


if let website = website {
print("Getting pdf: ",website)

if let pdf = NSBundle.mainBundle().URLForResource(website, withExtension: "pdf", subdirectory: nil, localization: nil){

print(pdf) // <-- this is always nil
let req = NSURLRequest(URL: pdf)

webView.loadRequest(req)
self.view.addSubview(webView)

}


}


What am I doing wrong? Needless to say, this is my very first app that I'm developing.

Answer Source

If the file is not in your app you should not use NSBundle.

let pdfUrl = NSURL(string: website)
let req = NSURLRequest(URL: pdfUrl)

I'm also not sure why you are adding the webView subview to the view. Shouldn't that be done somewhere else? Shouldn't you push a controller with the webview instead?