如何在cocoapods resource_bundle中加载资源

Joe*_*SHI 25 ios cocoapods

我在如何在cocoapods resource_bundle中加载资源方面遇到了很多困难.

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

s.source_files = 'XDCoreLib/Pod/Classes/**/*'
s.resource_bundles = {
'XDCoreLib' => ['XDCoreLib/Pod/Resources/**/*.{png,storyboard}']
}
Run Code Online (Sandbox Code Playgroud)

这就是我想从主项目中做的事情.

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

我确实看到了图片XDCoreLib.bundle,但它返回零.

小智 41

有一段时间我一直在努力解决类似的问题.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)
Run Code Online (Sandbox Code Playgroud)

  • 扩展@MattRobinson 所说的内容,您可以将“XDWebViewController.self”替换为 pod 内的任何类。该行代码的目标是通过使用属于框架(pod)的任何类来识别框架包 (3认同)
  • @Siddh XDWebViewController.self应该是pod内部的一个类。 (2认同)

Mat*_*son 8

我认为没有其他答案可以描述与Podspec的关系。束URL使用Pod的名称,然后.bundle查找资源束。此方法与资产目录配合使用,以访问容器内部和外部的容器图像。

Podspec

Pod::Spec.new do |s|
  s.name             = 'PodName'
  s.resource_bundles = {
    'ResourceBundleName' => ['path/to/resources/*/**']
  }
end
Run Code Online (Sandbox Code Playgroud)

目标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];
Run Code Online (Sandbox Code Playgroud)

迅速

看到这个答案


Sha*_*ssy 6

这会起作用

.podspec添加s.resourcess.resource_bundlespod install事后)

s.resources = 'XDCoreLib/Pod/Resources/**/*.{png,storyboard}'
Run Code Online (Sandbox Code Playgroud)

然后在您的代码中,其操作非常简单:

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

注意:您可能需要pod install在更新后运行,.podspec以对Xcode项目进行更改