访问pod中的资源

我想将图片资源包含在cocoapod库中,但是我无法访问它们。 我已阅读这些资源寻求帮助:

Cocoapods资源

Cocoapods资源包

Mokacoding资源包

大卫波特资源包

但是,没有人指出我获取资源的方向。 我已经尝试了以下内容:

[UIImage imageWithData:[NSData dataWithContentsOfURL:[(NSBundle *)[NSBundle bundleWithIdentifier:@"Assets"] URLForResource:@"my-image@2x" withExtension:@"png"]]] [UIImage imageWithData:[NSData dataWithContentsOfURL:[(NSBundle *)[NSBundle bundleWithIdentifier:@"Assets"] URLForResource:@"my-image" withExtension:@"png"]]] [UIImage imageWithData:[NSData dataWithContentsOfURL:[(NSBundle *)[NSBundle bundleWithIdentifier:@"Assets.bundle"] URLForResource:@"my-image" withExtension:@"png"]]] [UIImage imageWithData:[NSData dataWithContentsOfURL:[(NSBundle *)[NSBundle mainBundle] URLForResource:@"my-image" withExtension:@"png"]]] [[UIImage imageWithData:[NSData dataWithContentsOfURL:[(NSBundle *)[NSBundle mainBundle] URLForResource:@"my-image@2x" withExtension:@"png"]]] [UIImage imageNamed:@"my-asset"] [UIImage imageNamed:@"my-asset@2x.png"] 

但是他们都没有工作。

我已经安装了我的podspec这些替代品,既不与上述工作:

 s.resources = ['Pod/Assets/*.{png, jpg}', 'Pod/Assets/**/*.{png, jpg}'] s.resource_bundles = { 'Assets' => ['Pod/Assets/*.{png, jpg}', 'Pod/Assets/**/*.{png, jpg}'] } 

这些资源在pod update后显示在“Development Pods / My App / Resources”下,但我无法访问这些资源。 没有任何捆绑,没有任何名称为“资产”。

任何帮助或指导将不胜感激。

这取决于你使用的Cocoapods的版本。 使用老版本的cocoapods,你可以使用[NSBundle mainBundle]:pathForResource:ofType:

 NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"MyResourceBundle" ofType:@"bundle"]; NSBundle *bundle = [NSBundle bundleWithPath:bundlePath]; 

如果您使用的是较新的Cocoapods并在您的podspec文件中使用spec.resource_bundles而不是spec.resources,则必须避免使用mainBundle,并将其replace为NSBundle bundleForClass,它将“ 返回与指定类关联的NSBundle对象 ”

例:

 NSString *bundlePath = [[NSBundle bundleForClass:[MyFrameworkClass class]] pathForResource:@"MyResourceBundle" ofType:@"bundle"]; NSBundle *bundle = [NSBundle bundleWithPath:bundlePath]; 

这也使我绊倒了。 也许我误解了+bundleWithIdentifier:但我不认为你可以使用它来获取你的iOS应用程序包内的资源包。 有关更多详细信息,请参阅捆绑文档中的“通过标识符获取捆绑软件”部分。

什么工作是+bundleWithPath:例如:

 NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"MyResourceBundle" ofType:@"bundle"]; NSBundle *bundle = [NSBundle bundleWithPath:bundlePath]; 

我将其包装在dispatch_once块的内部,并在需要访问此捆绑包时随时调用它。

我在我的podspec中也使用了s.resource_bundles语法,而且这个工作正常。