Fuzzy
Fuzzy

Reputation: 842

URLForResource returns nil

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

Upvotes: 10

Views: 10033

Answers (5)

Song Bee
Song Bee

Reputation: 794

I met a same issue in a MAC application. After several hours, I found an easy way to fix it.

1, Make sure there is a phase named "Copy Files" under "Build Phases". If not, please add one.

2, Add your resources into the phase. enter image description here

3, Rebuild your project and you can find your resources located in ~/Library/Developer/Xcode/DerivedData//Build/Products/Debug/.

Upvotes: 0

quarac
quarac

Reputation: 3483

using this solved my problem [myBundle URLForResource: withExtension: subdirectory: ]

Subdirectory queries to NSBundle URLForResource need to specify the subdirectory. Otherwise it returns nil.

One hour figuring this today :'(

Upvotes: 0

olynoise
olynoise

Reputation: 2056

Quitting and restarting Xcode fixed this for me.

Upvotes: 0

Peter Brockmann
Peter Brockmann

Reputation: 3704

I had a similar problem. The answer for me was to check the Target Membership of object's identity. target membership must be selected for any object to be analyzed or accessed in the app

Upvotes: 8

Fuzzy
Fuzzy

Reputation: 842

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

Upvotes: 12

Related Questions