How can I load an image from Assets.car (compiled

2019-03-16 19:23发布

We're getting these kind of error messages:

Could not load the "iconStatus" image referenced from a nib in the bundle with identifier "com.company.OurResourceBundle".

Basically, we put a bunch of images in the xcassets folder ( which works for non-bundle loaded cases ). The xcassets and nib files are packed into a resource bundle.

When the app launches,

  1. uiimageview in the nib file cannot load any images with the above error message.
  2. [UIImage imageNamed:@"OurResourceBundle.bundle/iconStatus"] returns nil

The question is related to "How can I load an image from Assets.car (compiled version of xcassets) within an NSBundle?", but we don't use CocoaPods.

2条回答
来,给爷笑一个
2楼-- · 2019-03-16 19:46

I suspect if your image assets folder gets compressed into a .car file then NSBundle will know how to search for assets inside of it. Try creating a new bundle from your resources bundle. Then ask that bundle for the path of your image. Finally create an image from that path. This is sort of the approach we take when bundling image assets and localized strings with our static libraries. Our version is a little more involved as it takes care of things like @2x and ~ipad images automatically but this is the gist of it.

    NSBundle *myBundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"your bundle" ofType:@"bundle"]];
    NSString *filePath = [myBundle pathForResource:@"icon" ofType:@"png"];
    UIImage *image = [UIImage imageWithContentsOfFile:filePath];
查看更多
别忘想泡老子
3楼-- · 2019-03-16 20:11

In iOS 7 it is not possible to load images from any .car file aside from the one that Xcode compiles into the main bundle. This was confirmed by an Apple Developer at https://devforums.apple.com/message/968859#968859:

Unfortunately it is not possible to load images from any car file aside from the one that Xcode compiles into your main bundle, as +imageNamed: does not accept a bundle parameter, which is what is needed to do so (and even then it would only be able to open a single asset catalog in a single bundle).

In iOS 8 there is a new method that appears to do what you want:

+ (UIImage *)imageNamed:(NSString *)name inBundle:(NSBundle *)bundle
    compatibleWithTraitCollection:(UITraitCollection *)traitCollection
查看更多
登录 后发表回答