【问题标题】:How to use images asset catalog in cocoapod library for iOS如何在 iOS 的 cocoapod 库中使用图像资产目录
【发布时间】:2015-12-11 04:31:06
【问题描述】:

我有一个 cocoapod 库,其中包含 2 种格式的资产:

  • .storyboard
  • XCode 资产目录 .xcassets(带图片)

我的podspec 文件包含资源包的定义:

s.resource_bundle = {'SparkSetup' => ['Resources/**/*.{xcassets,storyboard}']}

我在 pod 项目中有一个单独的目标,通过使用这些文件 + 该包的 plist 文件来创建资源包。

事情是,当我在应用程序项目中使用 pod 时 - 我可以看到 pod 目标中的 storyboard/xcassets 文件,我可以轻松访问和运行故事板,但故事板中引用的图像(到 .xcassets文件)在运行时找不到(但在 IB 中正确显示)。

我得到的错误是:

Could not load the "spinner" image referenced from a nib in the bundle with identifier "(null)"

我确实在产品目录中看到了一个捆绑文件。 为了在我使用的故事板中实例化 VC:

+(NSBundle *)getResourcesBundle
{
    NSBundle *bundle = [NSBundle bundleWithURL:[[NSBundle mainBundle] URLForResource:@"SparkSetup" withExtension:@"bundle"]];
    return bundle;
}


+(UIStoryboard *)getSetupStoryboard
{
    UIStoryboard *setupStoryboard = [UIStoryboard storyboardWithName:@"setup" bundle:[SparkSetupMainController getResourcesBundle]];
    return setupStoryboard;
}

这似乎适用于查找故事板,但不适用于查找同一包中 .xcassets 中的图像。

我做错了什么?如何从这个故事板/代码中引用图像,并能够将此 UI pod 集成到任何应用程序中?

谢谢!

【问题讨论】:

  • 有完全相同的问题。我注意到,如果我使用没有资产目录的图像,它可以正常工作。
  • @bencallis 显然这是唯一的解决方案。 XCode 似乎无法引用主应用程序包中未加载的资产目录。唯一的解决方案是将 podspec 中的 resource_bundle 行更改为包含 .pngs 而不是 .xcasset 并单独引用每个图像。不完美,但这是它工作的唯一方式..
  • 也遇到了这个问题。甚至无法从 pod 内的 xcasset 目录加载带有 imageNamed 的图像。 :(

标签: ios objective-c iphone xcode cocoapods


【解决方案1】:

结合所有的答案,让复制粘贴到您的项目中变得容易:

class RandomClass: Any { } // Necessary for UIImage extension below
extension UIImage {
    convenience init?(fromPodAssetName name: String) {
        let bundle = Bundle(for: RandomClass.self)
        self.init(named: name, in: bundle, compatibleWith: nil)
    }
}

不要忘记将您的资产目录添加到您的 .podspec 文件中:

s.resource_bundles = {
    'Resources' => ['YourPodName/*.xcassets']
}

【讨论】:

    【解决方案2】:

    如果您使用的是 SwiftUI,则使用 Image.init(_ name: String, bundle: Bundle?) 初始化程序将不起作用,您必须像这样初始化它:

     func getImage(named name: String) -> UIImage {
        // Use a random singleton class in your project.
        // Emphasis on class, structs won't work.
        let bundle = Bundle(for: [random class].self)
    
        if let image = UIImage(named: name, in: bundle, compatibleWith: nil) {
            return image
        }
    
        return .init()
    }
    
    Image(uiImage: getImage(named: "image_name"))
    

    【讨论】:

      【解决方案3】:

      至少从 Cocoapods 1.0.1 版开始,支持图像资产目录。

      在我的 Swift 4.2 代码中,我使用了:

      public static var GoogleIcon: UIImage {
          let bundle = Bundle(for: self)
          log.msg("bundle: \(bundle)")
          return UIImage(named: "GoogleIcon", in: bundle, compatibleWith: nil)!
      }
      

      在我的 pod 规范中,我使用了:

      s.resources = "SMCoreLib/Assets/*.xcassets"
      

      当我使用模拟器构建时,.car 文件确实显示在框架中:

      cd /Users/<snip>/SMCoreLib.framework 
      ls
      Assets.car  Info.plist  SMCoreLib
      

      【讨论】:

      • s.resources = "SMCoreLib/Assets/*.xcassets" 这节省了我的时间,谢谢:)
      • 是的,但这包括应用程序目标内的资源,而不是 Pod 框架的一部分。
      • @MichK 我不太明白你在说什么。 AFAIK 图像资源 do 保存在 Pod 的包中。因此需要像上面那样为 Pod 使用 NSBundle。
      • @ChrisPrince 我的意思是,通过使用 s.resources 您将资源文件添加到主应用程序包中,但是当您使用 s.resource_bundle 时,您将资源文件添加到单独的包中,然后将其添加到主应用程序捆。在我看来,第二个选项提供了更好的分离,但 podspec 的用户可以同时使用这两种方法,这取决于项目规范和偏好。
      • @MichK 只有在静态集成 Pod 时才会出现这种情况。当使用_frameworks!使用选项,s.resources 做正确的事并添加标准框架资源。
      【解决方案4】:

      如果没有上述解决方案,我仍然无法让它工作。 我的 Pod 中有一个 Assets.xcassets 文件。

      在我的 Pod 类中,我想访问资产中的图像

      这样指定:

      s.resource_bundles = {
           'SWDownloadPlayButton' => ['SWDownloadPlayButton/Assets/Assets.xcassets']
      }
      

      有了这个助手:

      public struct ImagesHelper {
          private static var podsBundle: Bundle {
              let bundle = Bundle(for: SWDownloadPlayButton.self)
              return Bundle(url: bundle.url(forResource: "SWDownloadPlayButton",
                                            withExtension: "bundle")!)!
          }
      
          private static func imageFor(name imageName: String) -> UIImage {
              return UIImage.init(named: imageName, in: podsBundle, compatibleWith: nil)!
          }
      
          public static var download_icon: UIImage {
              return imageFor(name: "download_icon")
          }
      }
      

      但是无论我在我的 Pod 类中做什么(不在示例项目中)......就像这样

       var centerImage: UIImage = ImagesHelper.download_icon.withRenderingMode(.alwaysTemplate) {
              didSet {
                  updateImage()
              }
          }
      

      我仍然在 centerImage 上得到一个 nil

      【讨论】:

      • 找到了!!不能在这样的属性中工作,但在 de class init 方法中它工作正常!所有方法:)
      【解决方案5】:

      我自己对 CocoaPods 问题的解决方案。我没有使用 UIImage,而是向 Bundle 添加了一个方法。该方法尝试定位给定名称的内部包,但回退到原始包。这允许代码在使用 pod 的应用程序代码以及 pod 代码本身中工作。

      extension Bundle {
      
          /**
           Locate an inner Bundle generated from CocoaPod packaging.
      
           - parameter name: the name of the inner resource bundle. This should match the "s.resource_bundle" key or
             one of the "s.resoruce_bundles" keys from the podspec file that defines the CocoPod.
           - returns: the resource Bundle or `self` if resource bundle was not found
          */
          func podResource(name: String) -> Bundle {
              guard let bundleUrl = self.url(forResource: name, withExtension: "bundle") else { return self }
              return Bundle(url: bundleUrl) ?? self
          }
      }
      

      然后在viewDidLoad 方法或其他任何你有图像设置代码的地方,输入类似这样的内容,其中“ClassFromPod”指的是来自 CocoaPod 的 Swift 类,“ResourceName”是内部包的名称pod(您应该能够在“Pods/Projects”中使用 Xcode 项目导航器查看捆绑包——嵌入式捆绑包有一个 LEGO 图标并有一个“捆绑包”后缀。)

      super.viewDidLoad()
      let bundle = Bundle(for: ClassFromPod.self).podResource(name: "ResourceName")
      img1 = UIImage(named: "FancyBase", in: bundle, compatibleWith: nil)
      img2 = UIImage(named: "FancyHandle", in: bundle, compatibleWith: nil)
      

      如您所见,UIImage API 保持不变,只是使用的包不同,具体取决于它在运行时找到的内容。

      【讨论】:

        【解决方案6】:

        在您的 pod 规范的资源中添加您的 .xcassets 文件,并使用以下 UIImage 初始化:

        extension UIImage {
            convenience init?(podAssetName: String) {
                let podBundle = Bundle(for: ConfettiView.self)
        
            /// A given class within your Pod framework
            guard let url = podBundle.url(forResource: "CryptoContribute",
                                          withExtension: "bundle") else {
                return nil
        
            }
        
            self.init(named: podAssetName,
                      in: Bundle(url: url),
                      compatibleWith: nil)
            }
         }
        

        【讨论】:

          【解决方案7】:

          您可以使用 pod 的 bundle id 从 pod 访问图像

           NSBundle * bundle = [NSBundle bundleWithIdentifier:@"bundle id of your pod"];
          UIImage * image = [UIImage imageNamed:@"imageName" inBundle:bundle compatibleWithTraitCollection:nil];
          

          【讨论】:

            【解决方案8】:

            在你的 podspec 中这样做

            s.resources = 'RootFolder/**/*.{lproj,storyboard,xcdatamodeld,xib,xcassets,json}'
            

            【讨论】:

              【解决方案9】:

              只有这对我有用(Swift 3 和 Swift 4)

              public struct ImagesHelper {
                private static var podsBundle: Bundle {
                  let bundle = Bundle(for: YourClass.self)
                  return Bundle(url: bundle.url(forResource: "YourClass",
                                                withExtension: "bundle")!)!
                }
              
                private static func imageFor(name imageName: String) -> UIImage {
                  return UIImage.init(named: imageName, in: podsBundle, compatibleWith: nil)!
                }
              
                public static var myImage: UIImage {
                  return imageFor(name: "imageName")
                }
              }
              

              然后按如下方式使用:

              ImagesHelper.myImage
              

              就像@Chris Prince 的回答一样,不要忘记更新您的 podspec 文件,例如:

              s.resource_bundles = {
                'YourClass' => ['YourPodName/*/Assets.xcassets']
              }
              

              【讨论】:

              • 设置 s.resources 和 resource_bundles 应该可以正常工作
              【解决方案10】:

              Swift 3 版本

              private func getImageFromBundle(name: String) -> UIImage {
                 let podBundle = Bundle(for: YourClass.self)
                 if let url = podBundle.url(forResource: "YourClass", withExtension: "bundle") {
                    let bundle = Bundle(url: url)
                    return UIImage(named: name, in: bundle, compatibleWith: nil)!
                 }
                 return UIImage()
              }
              

              【讨论】:

                【解决方案11】:

                如果你使用的是 swift。

                class func loadImage(name: String) -> UIImage? {
                    let podBundle = NSBundle(forClass: MyClass.self)
                    if let url = podBundle.URLForResource("MyBundleName", withExtension: "bundle") {
                        let bundle = NSBundle(URL: url)
                        return UIImage(named: name, inBundle: bundle, compatibleWithTraitCollection: nil)
                    }
                    return nil
                }
                

                【讨论】:

                • MyClass 指的是什么?
                【解决方案12】:

                好吧,pod 不支持图像资产目录 - 只需在 podspec 中包含一个包含图像文件的资源包,如下所示:

                s.subspec 'Resources' do |resources|
                    resources.resource_bundle = {'MyBundle' => ['Resources/**/*.{png}']}
                
                end
                

                然后像这样从 pod 中安全地访问图像:

                +(NSBundle *)getResourcesBundle
                {
                    NSBundle *bundle = [NSBundle bundleWithURL:[[NSBundle bundleForClass:[self class]] URLForResource:@"MyBundle" withExtension:@"bundle"]];
                    return bundle;
                }
                
                
                +(UIImage *)loadImageFromResourceBundle:(NSString *)imageName
                {
                    NSBundle *bundle = [MyClass getResourcesBundle];
                    NSString *imageFileName = [NSString stringWithFormat:@"%@.png",imageName];
                    UIImage *image = [UIImage imageNamed:imageFileName inBundle:bundle compatibleWithTraitCollection:nil];
                    return image;
                }
                

                这解决了在 cocoapod 中处理图像/资源的所有问题。

                【讨论】:

                • 是否也可以通过这种方式从情节提要中获取图像?
                • @swalkner 在情节提要中,您必须在 UIImageView 图像 id 中添加 MyBundleName.bundle/&lt;imagename&gt;.png,它仅在运行时可用。无法预览。
                猜你喜欢
                • 1970-01-01
                • 2014-12-06
                • 2017-01-16
                • 2016-10-16
                • 2018-09-16
                • 1970-01-01
                • 2015-01-10
                • 2017-10-27
                相关资源
                最近更新 更多