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

一、资源文件引用的方式

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

1-一、resource_bundles

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

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

CocoaPods 官方强烈推荐使用 resource_bundles,由于用 key-value 能够避免相同名称资源的名称冲突。app

同时建议 bundle 的名称至少应该包括 Pod 库的名称,能够尽可能减小同名冲突优化

Examples:ui

ss.resource_bundles = {
          'KZWUI' => 'KZWUtils/Assets/*.xcassets'
      }
复制代码

1-二、 resources

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

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中将会有莫名其妙的问题,因此最好在封装库的不要这么去作。spa

Examples:code

s.resource  = "MGFaceIDLiveCustomDetect.bundle"
复制代码

二、图片资源管理

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

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

ss.resource_bundles = {
          'KZWUI' => 'KZWUtils/Assets/*.xcassets'
      }
复制代码

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

三、 总结

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。

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

相关文章
相关标签/搜索