0

I am to load html file in my webview. The files contain references to /css and /images sub directories. So, I found the following from this answer.

    let path: String? = NSBundle.mainBundle().pathForResource("Ace-VetBolus", ofType: "html", inDirectory: "HTMLFiles")
    let requestURL = NSURL(string:path!);
    let request = NSURLRequest(URL:requestURL!);

    web1.loadRequest(request)

And I cannot resolve this issue: fatal error: unexpectedly found nil while unwrapping an Optional value at the second line.

Community
  • 1
  • 1
A. K. M. Tariqul Islam
  • 2,824
  • 6
  • 31
  • 48

2 Answers2

1

Using ! forcefully unwraps a value, so if it's nil, you're going to get a fatal error as you see.

You want to use an if let statement or a guard statement.

let path: String? = NSBundle.mainBundle().pathForResource("Ace-VetBolus", ofType: "html", inDirectory: "HTMLFiles")
if let unwrappedPath = path {
    let requestURL = NSURL(string: unwrappedPath)
    let request = NSURLRequest(URL: requestURL)

    web1.loadRequest(request)
}

Using guard in Swift 2 functions like so:

let path: String? = NSBundle.mainBundle().pathForResource("Ace-VetBolus", ofType: "html", inDirectory: "HTMLFiles")
guard let unwrappedPath = path else {
    return // or handle fail case some other way
}
let requestURL = NSURL(string: unwrappedPath)
let request = NSURLRequest(URL: requestURL)
web1.loadRequest(request)

Biggest different is the guard pattern allows you to keep the unwrapped variable in the same scope, while if let creates a new scope.

Brendan Molloy
  • 1,784
  • 14
  • 22
  • NSURL(string:) it is only for web links, not for local resources. When creating NSURL for local file resources you need to use init(fileURLWithPath path: String). https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/#//apple_ref/occ/instm/NSURL/initFileURLWithPath: – Leo Dabus Dec 01 '15 at 06:53
  • Fair enough, I was just looking at the specific question, not the underlying APIs. :) – Brendan Molloy Dec 01 '15 at 06:54
  • No no, I understood your comment, I am saying I merely wrapped it naively in an if let assuming that the OP was using an API correctly. I will look closer next time. :) – Brendan Molloy Dec 01 '15 at 06:59
0

You should use NSBundle method URLForResource:

if let url = NSBundle.mainBundle().URLForResource("Ace-VetBolus", withExtension: "html", subdirectory: "HTMLFiles") {
    let requestURL = NSURLRequest(URL: url)
    web1.loadRequest(requestURL)
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571