Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URLForResource returns nil

Tags:

xcode

I'm in the process of learning how to use xcode and how to write applications for the Mac.

So, I have a simple screensaver that loads an external file which works fine. I decided that it would be better to embed the html source in the application to reduce the external dependancies.

I dragged the HTML file to the resources folder, it's at the top level there's no sub folder or anything.

resource added

I made sure the Add to targets had my application in it, along with selecting 'create folder references' and 'copy files if needed'. I use the following to get the url to the file, but it returns nil

    NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:@"embedded" withExtension:@"html"];


 System Preferences[10185]: fileUrl returned (null) 

I've read through all the other SO issues for the similar problems but none of the fixes seem to apply. I've gone through and checked them.

If I show the package contents of the final build the embedded.html is in there. Am I missing something really obvious?

edit to add

In build phases it's listed in Copy Bundle Resources

enter image description here

xcode version is 6.1.1

like image 797
Fuzzy Avatar asked Jan 17 '15 11:01

Fuzzy


1 Answers

After some considerable digging and a smidgeon of luck I found that

    NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:@"embedded" withExtension:@"html"];

is incorrect and I should be using

    NSURL *fileUrl = [[NSBundle bundleForClass:[self class]] URLForResource:@"embedded" withExtension:@"html"];

instead.

i.e. NSBundle bundleForClass:[self class] and not NSBundle mainBundle will give access to a screensaver bundle.

Might be obvious, but only if you know ;)

See Apple Developer NSBundle Class Reference

like image 112
Fuzzy Avatar answered Oct 11 '22 17:10

Fuzzy