如何在cocoapods中加载资源resource_bundle

问题描述:

我一直在为如何加载cocoapods resource_bundle中的资源而苦苦挣扎。如何在cocoapods中加载资源resource_bundle

以下是我在.podspecs文件中的内容。

s.source_files = 'XDCoreLib/Pod/Classes/**/*' 
s.resource_bundles = { 
'XDCoreLib' => ['XDCoreLib/Pod/Resources/**/*.{png,storyboard}'] 
} 

这就是我想要从主项目中做的。

let bundle = NSBundle(forClass: XDWebViewController.self) 
let image = UIImage(named: "ic_arrow_back", inBundle: bundle, compatibleWithTraitCollection: nil) 
print(image) 

我看过XDCoreLib.bundle中的图片,但返回nil。

+0

这样不行,只是复制这些资源到你的项目,因为这些资源在吊舱可随时更新/删除。 –

+1

这个吊舱由我们自己维护。项目规模越来越大,我们希望将每个模块分开。 –

我在一段时间内遇到了类似的问题。资源包实际上是一个与您的代码所在位置不同的捆绑包。请尝试以下操作:

let frameworkBundle = NSBundle(forClass: XDWebViewController.self) 
let bundleURL = frameworkBundle.resourceURL?.URLByAppendingPathComponent("XDCoreLib.bundle") 
let resourceBundle = NSBundle(URL: bundleURL!) 
let image = UIImage(named: "ic_arrow_back", inBundle: resourceBundle, compatibleWithTraitCollection: nil) 
print(image) 
+0

太棒了!我错过了“URLByAppending”,谢谢 –

+0

@ Quaid XDWebViewController.self在第一行什么是 – Siddh

+0

@Siddh'XDWebViewController.self'应该是一个类中的类。 –

有趣的事情是,当你需要做的是在同样的cocoapod库 我面对我的荚使用的厦门国际银行和的plist文件时的源文件。

这是在下一个方法解决。加载厦门国际银行文件的示例:

let bundle = Bundle(for: self.classForCoder) 
let viewController = CocoapodViewController(nibName: "CocoapodViewController", bundle: bundle) 

我不认为任何其他的答案中所描述的Podspec的关系。软件包URL使用该容器的名称,然后使用.bundle来查找资源包。此方法适用于资产目录,以访问吊舱内外的吊舱图像。

Podspec

Pod::Spec.new do |s| 
    s.name    = 'PodName' 
    s.resource_bundles = { 
    'ResourceBundleName' => ['path/to/resources/*/**'] 
    } 
end 

目标C

// grab bundle using `Class` in pod source (`self`, in this case) 
NSBundle *bundle = [NSBundle bundleForClass:self.classForCoder]; 
NSURL *bundleURL = [[bundle resourceURL] URLByAppendingPathComponent:@"PodName.bundle"]; 
NSBundle *resourceBundle = [NSBundle bundleWithURL:bundleURL]; 
UIImage *podImage = [UIImage imageNamed:@"image_name" inBundle:resourceBundle compatibleWithTraitCollection:nil]; 

夫特

参见this answer

只是为了记录:我想打开存储在CocoaPods库中的类别的NIB。当然[self classForCoder]回到UIKit(因为类别),所以上面的方法不起作用。

我使用一些硬编码的路径,解决了这个问题:

NSURL *bundleURL = [[[NSBundle mainBundle] resourceURL] URLByAppendingPathComponent:@"Frameworks/MyCocoaPodLibraryName.framework"]; 
NSBundle *podBundle = [NSBundle bundleWithURL:bundleURL]; 

CustomView *customView = [[podBundle loadNibNamed:@"CustomView" owner:self options:nil] firstObject]; 

这会在你的代码工作

.podspec除了添加s.resourcess.resource_bundlespod install后)

s.resources = 'XDCoreLib/Pod/Resources/**/*.{png,storyboard}' 

然后,它很容易:

let image = UIImage(named: "image_name.png", in: Bundle(for: type(of: self)), compatibleWith: nil) 

您可以通过选择Pods项目,选择所需的目标并确保您位于General选项卡上来检查Bundle的ID。

enter image description here

然后在代码中,你可以加载说在波德图像,像这样:

backgroundImageView.image = UIImage(named: "business_fellas", in: Bundle(identifier: "org.cocoapods.StandardLibrary3-0"), compatibleWith: nil)