Reputation: 5936
When loading a local resource file in a mac app
let urlpath = NSBundle.mainBundle().pathForResource("myResource", ofType: "html");
Converting the resource path to a string
for NSURL
always returns nil
println("resource path = \(urlpath)") <---resource logged ok
web.frameLoadDelegate = self;
let requesturl = NSURL(string: urlpath!)
println("URL String = \(requesturl)"),<---- returns nil
let request = NSURLRequest(URL: requesturl!)
web.mainFrame.loadRequest(request)
Which presumably is why im getting the error found nil while unwrapping an Optional value
What am I missing here to correctly convert the pathForResource
to a string
?
Upvotes: 1
Views: 2831
Reputation: 16090
For Swift 5
let path = Bundle.main.path(forResource: "myResource", ofType: "html")
let url = URL(fileURLWithPath: path!)
Upvotes: 1
Reputation: 540145
The code given in Leonardo's answer should work and is the easier and safer method with optional binding. Here is an explanation why your code fails:
let requesturl = NSURL(string: urlpath!)
returns nil
because urlpath
is a file path and not an URL string
(such as "file:///path/to/file").
If you replace that line with
let requesturl = NSURL(fileURLWithPath: urlpath!)
then you will get the expected output.
Upvotes: 1
Reputation: 236568
if let myFileUrl = NSBundle.mainBundle().URLForResource("yourFile", withExtension: "html"){
// do whatever with your url
}
Upvotes: 4