访问pod中的资源

Ril*_*eyE 14 xcode resourcebundle uiimage ios cocoapods

我想在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"]
Run Code Online (Sandbox Code Playgroud)

但它们都不起作用.

我已经使用这些替代方案设置了podspec,并且不能使用上述方法:

s.resources = ['Pod/Assets/*.{png, jpg}', 'Pod/Assets/**/*.{png, jpg}']
s.resource_bundles = {
    'Assets' => ['Pod/Assets/*.{png, jpg}', 'Pod/Assets/**/*.{png, jpg}']
}
Run Code Online (Sandbox Code Playgroud)

资源显示在"开发窗口/我的应用程序/资源"之后pod update,但是在我的生命中我无法访问它们.没有任何捆绑,也没有任何名为"资产"的东西.

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

Hug*_*ugh 9

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

NSString *bundlePath = [[NSBundle mainBundle] 
    pathForResource:@"MyResourceBundle" ofType:@"bundle"];
NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
Run Code Online (Sandbox Code Playgroud)

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

例:

NSString *bundlePath = [[NSBundle bundleForClass:[MyFrameworkClass class]] 
    pathForResource:@"MyResourceBundle" ofType:@"bundle"];
NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
Run Code Online (Sandbox Code Playgroud)


scl*_*age 5

这也让我感到沮丧.也许我误解了+bundleWithIdentifier:,但我认为你不能用它来获取你的iOS应用程序包内的资源包.有关详细信息,请参阅捆绑文档的"按标识符获取捆绑包"部分.

工作是什么+bundleWithPath:,例如:

NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"MyResourceBundle" ofType:@"bundle"];
NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
Run Code Online (Sandbox Code Playgroud)

我把它包装在一个dispatch_once块内,并在我需要访问这个包时调用它.

s.resource_bundles也在我的podspec中使用语法,这可以正常使用它.