Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSbundle pathforresource not finding file

I have images.xcassets listed ounder copy bundle resources, and I did try to just state the file name by itself: MSB_big_icon , before trying to add the path within images.xcassets.

Can anybody tell me what I'm doing wrong?

NSString *path = [[NSBundle mainBundle]pathForResource:@"/Raymio_android_images/MSB_big_icon.imageset/MSB_big_icon" ofType:@"png"];
NSLog(@"path: %@", path);
MSBIcon *tilecon = [MSBIcon iconWithUIImage:[UIImage imageWithContentsOfFile:path] error:&error];
like image 581
DevilInDisguise Avatar asked Nov 01 '22 06:11

DevilInDisguise


1 Answers

David Ansermot is right that xcassets is a much better approach and strongly preferred. If you can't use that (running on older versions of iOS for instance), still put everything in one directory and use imageNamed:. This has significant caching benefits over hand-loading the file.

An asset catalog (xcassets) is a (relatively) new, unified way of managing image resources. The images are no longer accessible as separate files on the disk. Instead, imageNamed: consults the asset catalog and fetches the correct asset.

Prior to asset catalogs (and still, for non-images), assets were stored in localized directories. All of your unlocalized assets would be put into a directory called Resources (no matter where those files might appear to be in your source tree, and no matter how those files might be arranged in your Xcode folders). Localized files would be stored in directories like English.lproj or French.lproj. When you make NSBundle calls to load MyImage, it looks at each localized directory in the order the user has configured, and if it cannot find it in any of those directories, it looks in Resources.

Now it is possible to store full directories as "a resource" by marking them as directory references in Xcode. In that case, the whole directory would be copied into Resources or the appropriate localized directory. In order to find files inside such a directory you can use the ...inDirectory: version of the NSBundle methods. So most of the time, you want to just use imageNamed:, which is going to fetch things out of the asset catalog if available, and then search localized directories, and then look in Resources. If you need to find a non-image, or if for some reason you want the real path to the file, you can compute it like this:

NSString *path = [[NSBundle mainBundle] pathForResource:@"MSB_big_icon" ofType:@"png"];

And if that resource were in a directory tree (because it was a directory reference in Xcode), you can access it like this:

NSString *path = [[NSBundle mainBundle] pathForResource:@"MSB_big_icon"
                                                 ofType:@"png" 
                                            inDirectory:@"Raymio_android_images/MSB_big_icon.imageset"];
like image 129
Rob Napier Avatar answered Nov 15 '22 06:11

Rob Napier