2014-09-12 119 views
13

我想将图片资源包含在cocoapod库中,但我无法访问它们。我读过这些资源的帮助:pod中的访问资源

Cocoapods Resources

Cocoapods Resource Bundles

Mokacoding Resource Bundles

David Potter Resource Bundles

然而,没有点我在访问资源的方向。我已经试过如下:

[UIImage imageWithData:[NSData dataWithContentsOfURL:[(NSBundle *)[NSBundle bundleWithIdentifier:@"Assets"] URLForResource:@"[email protected]" 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:@"[email protected]" withExtension:@"png"]]] 
[UIImage imageNamed:@"my-asset"] 
[UIImage imageNamed:@"[email protected]"] 

但他们没有工作。

我设置我的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后,但我不能访问它们为了我的生活。没有任何捆绑,并且没有任何名为“资产”的东西。

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

+0

你两者都做's.resources'和's.resource_bundles'或单独审判呢?也许有一些冲突。 – 2014-09-14 07:42:20

+0

@NiklasBerglund分别。 – RileyE 2014-09-14 21:21:42

回答

5

这也绊住了我。也许我误解+bundleWithIdentifier:,但我不认为你可以使用它来获取iOS应用程序包内的资源包。有关更多详细信息,请参阅软件包文档的"Getting Bundles by Identifier"部分。

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

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

我包裹dispatch_once块里面并调用它任何时候我需要访问这个包。

我在我的podspec中也使用s.resource_bundles语法,并且它可以正常工作。

9

这取决于您使用的Cocoapods版本。 pathForResource:ofType:与旧版本的CocoaPods的,你可以使用[一个NSBundle mainBundle]脱身

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

如果您正在使用新的CocoaPods和使用spec.resource_bundles代替spec.resources在podspec文件,你必须避免mainBundle和替换它与一个NSBundle bundleForClass,其中 “Returns the NSBundle object with which the specified class is associated

例子:

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

谢谢 - 我会研究这个 – RileyE 2015-08-31 17:30:47

+0

作为一个扩展,我发现这不适用于从位于Cocapod中的资产目录加载图像。更多信息在这里:http://stackoverflow.com/a/23903860/235290我证实了这一点与我的同事们也证实,没有已知的方式做到这一点。所以你必须使用独立的图像文件而不是资产目录。 – Hugh 2015-10-06 20:22:39