封裝獨立庫時資源引用方式探討

一、資源文件引用的方式

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。

有時間會寫一篇詳細的靜態庫和動態庫的異同點和開發時遇到的坑。

相關文章
相關標籤/搜索