如何在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的图片,但它返回一个零。

我在一段时间里也遇到类似的问题。 一个pod的资源包实际上是你的代码所在的地方的一个独立的包。 尝试以下操作:

 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) 

我不认为其他答案已经描述了与Podspec的关系。 包URL使用pod的名称,然后使用.bundle来查找资源包。 此方法可与资产目录一起使用,以访问吊舱内外的吊舱图像。

Podspec

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

Objective-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]; 

迅速

看到这个答案 。

这将工作

.podspec添加s.resources以及s.resource_bundles (之后的pod install

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

那么在你的代码中,就像:

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

有趣的是,当你需要在cocoapod库中的源文件中使用xib和plist文件时,我也遇到了这个问题。

这在下一个方面解决了。 加载一个xib文件的例子:

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

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

我使用一些硬编码path解决了这个问题:

 NSURL *bundleURL = [[[NSBundle mainBundle] resourceURL] URLByAppendingPathComponent:@"Frameworks/MyCocoaPodLibraryName.framework"]; NSBundle *podBundle = [NSBundle bundleWithURL:bundleURL]; CustomView *customView = [[podBundle loadNibNamed:@"CustomView" owner:self options:nil] firstObject]; 

您可以通过selectPods项目,select所需的目标,并确保您位于常规选项卡上来检查Bundle的ID。

在这里输入图像说明

然后在代码中,你可以像这样在Pod中加载一个图像:

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