NSURL/NSURLRequest is unexpectedly nil

530 views Asked by At

I'm trying to load a PDF into a UIWebView, but when using loadRequest, I'm getting the error unexpectedly found nil while unwrapping an Optional. My relevant code is below:

    let url = NSURL(string: "http://www.urartuuniversity.com/content_images/pdf-sample.pdf")!

    println(url.fileURL)

    println("The URL is \(url.absoluteURL!)")

    let request = NSURLRequest(URL: url)

    webView.loadRequest(request)

The second line of code outputs false (unsurprisingly), but the third outputs the correct URL. webView is a connected UIWebView.

I've looked at a few examples of similar errors yet none seemed applicable, especially because the NSURL appears to be working due to the URL.absoluteURL! correctly outputting, as did numerous other similar commands.

I've also seen references to RFC 2396, but when looking at W3's documentation, my URL appears to be following these guidelines, but if it doesn't, then please tell me what the format is and how to change the URL (because I will have to literally change thousands more, and this PDF is merely an example PDF I found online).

When looking in the debug section, url is a NSURL and the place holding its value says the URL of the PDF, rather than a memory address, which could contribute partly to some of my problems.

Edit: To make my situation even weirder, because I'm using a universal app with a split-view and a table view, when I load an iPad, the PDF loads correctly, but the moment I go back to the master view and click on something, reloading the detail view, the fatal exception is found. If this made no sense, please tell me and I'll try to make it more comprehensible.

1

There are 1 answers

3
matt On BEST ANSWER

The problem is that you do not know what is nil. Add more logging, like this:

let url = NSURL(string: "http://www.urartuuniversity.com/content_images/pdf-sample.pdf")!
let request = NSURLRequest(URL: url)
println(url)
println(request)
println(webView)
webView.loadRequest(request)

In this way, by putting your app through its paces and trying to reproduce the crash, you will discover, just before the crash, exactly what is nil. I'm guessing it's the webView, but guessing is not programming — and the problem is that, so far, you are just guessing. Don't guess. You have a debugger! Debug!!!