Pod库中Bundle资源的管理

873 阅读1分钟

Pod指定方式

resources

 spec.resources = "AndyModule/**/*.{xib,png}"

资源文件在build 时会被拷贝到App的 mainBundle 里,会导致和主工程资源文件名冲突。

resource_bundles

spec.resource_bundles = {
    'AndyModuleResources' => ['AndyModule/**/*.{xib,png,xcassets}']
  }
  • resource_bundles就是为了解决命名冲突的问题,CocoaPods0.23.0 加入的新属性。

  • resource_bundles会自动生成AndyModuleResources.bundle把资源文件打包进去,resources方式则不会,就会导致冲突。

可以将工程build之后,Products - xxx.app - Show in Finder - 显示包内容

可以看到【AndyModuleResources.bundle】文件

推荐使用resource_bundles方式

图片使用方式

扩展UIImage结合定义结构体常量

# Podfile中use_frameworks!对Bundle资源的影响

struct CPConstants {
    private static let podName = "CP"
    private static let bundleName = "CPResource"

    static var main: Bundle {
        guard let bundlePath = mainPath, !bundlePath.isEmpty else { fatalError(bundleName + " resources not found!") }
        return Bundle(path: bundlePath) ?? Bundle.main
    }

    static var mainPath: String? {
        let bundlePath = Bundle.main.path(forResource: bundleName, ofType: "bundle")
        // bundle文件在动态库Frameworks的目录下

        let url = Bundle.main.url(forResource: "Frameworks/"+podName, withExtension: "framework")

        if let url = url {
            bundlePath = Bundle.init(url: url)?.path(forResource: bundleName, ofType: "bundle")
        }
        return bundlePath
    }
}

extension UIImage {
    convenience init?(cpNamed: String) {
        self.init(named: cpNamed, in: CPConstants.main, compatibleWith: nil)
    }
}