封装独立库时资源引用方式探讨

1,108 阅读3分钟

1、资源文件引用的方式

CocoaPods 两种资源文件引用的方式——resource_bundles & resources

1-1、resource_bundles

resource_bundles 允许定义当前 Pod 库的资源包的名称和文件。用 hash 的形式来声明,key 是 bundle 的名称,value 是需要包括的文件的通配 patterns。

We strongly recommend library developers to adopt resource bundles as there can be name collisions using the resources attribute.

CocoaPods 官方强烈推荐使用 resource_bundles,因为用 key-value 可以避免相同名称资源的名称冲突。

同时建议 bundle 的名称至少应该包括 Pod 库的名称,可以尽量减少同名冲突

Examples:

ss.resource_bundles = {
          'KZWUI' => 'KZWUtils/Assets/*.xcassets'
      }

1-2、 resources

使用 resources 来指定资源,被指定的资源只会简单的被 copy 到目标工程中(主工程)。

We strongly recommend library developers to adopt resource bundles as there can be name collisions using the resources attribute. Moreover, resources specified with this attribute are copied directly to the client target and therefore they are not optimised by Xcode.

官方认为用 resources 是无法避免同名资源文件的冲突的,同时,Xcode 也不会对这些资源做优化。

使用这种方式如果以[NSBundle mainBundle]形式加载资源,在use_frameworks!中会导致资源无法加载到。这时候你只能在podspec中配置 s.static_framework = true,这就造成你的库只能以静态的形式加载,在项目中可能会发生 framework not found,解决办法是在Build Settings -> Search Paths -> Framework Search Paths中将你的库加上去。同时写死静态库在Swift中将会有莫名其妙的问题,所以最好在封装库的不要这么去做。

Examples:

s.resource  = "MGFaceIDLiveCustomDetect.bundle"

2、图片资源管理

我们熟知平常用的 @2x @3x 图片是为了缩小用户最终下载时包的大小,通常我们会将图片放在 .xcassets 文件中管理,使用 .xcassets 不仅可以方便在 Xcode 查看和拖入图片,同时 .xcassets 最终会打包生成为 Assets.car 文件。对于 Assets.car 文件,App Slicing 会为切割留下符合目标设备分辨率的图片,可以缩小用户最终下载的包的大小。

所以我建议在pod中也同样以.xcassets来管理图片,所以资源的引用就是

ss.resource_bundles = {
          'KZWUI' => 'KZWUtils/Assets/*.xcassets'
      }

这种形式的,图片都在目录下的xcassets中,方便查看和使用。

3、 总结

resource_bundles 优点:

可以使用 .xcassets 指定资源文件 可以避免每个库和主工程之间的同名资源冲突

resource_bundles 缺点:

获取图片时可能需要使用硬编码的形式来获取:[[NSBundle bundleForClass:[self class]].resourcePath stringByAppendingPathComponent:@"/KZWUI.bundle"]

resources 优点:

可以使用 .xcassets 指定资源文件

resources 缺点:

会导致每个库和主工程之间的同名资源冲突 不需要用硬编码方式获取图片:[NSBundle bundleForClass:[self class]] compatibleWithTraitCollection:nil];

NSString* imagePathStr = [[[NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:IDCardBundleKey ofType:nil]] resourcePath] stringByAppendingPathComponent:[NSString stringWithFormat:@"image/%@", imageNameStr]];
UIImage* image = [UIImage imageWithContentsOfFile:imagePathStr];

So,一般来说使用 resource_bundles 会更好,不过关于硬编码,还可以再找找别的方式去避免。

上面大部分东西在别的文章都能找到,我主要是说下资源引用方式不同的原因造成的静态库和动态库加载在Swift中造成的后果,为了更好的兼容性所以还是需要用resource_bundles。

有时间会写一篇详细的静态库和动态库的异同点和开发时遇到的坑。