resource_bundles
spec.resource_bundles = {
'MyLibrary' => ['Resources/*.png'],
'OtherResources' => ['OtherResources/*.png']
}
resource_bundles顯式地做了 bundle 層面的分組
上面的寫法意思是在你的framework下生成MyLibrary.bundle和OtherResources.bundle
坑
- 使用了Resources/**/*的寫法 導(dǎo)致Resources下的目錄和文件 遞歸的被copy到Resources目錄下 造成資源的重復(fù)
以下是常用方式
spec.resource_bundles = {
'MyLibrary' => ['Resources/source'], // Resources/source文件夾下的所有內(nèi)容包括子文件夾
'MyLibrary1' => ['Resources/{source,source2}'], // Resources/source和Resources/source1文件夾下的所有內(nèi)容包括子文件夾
'MyLibrary2' => ['Resources/**/*.{png,xib}'], // Resources/source文件夾下的所有.png結(jié)尾的圖片和xib文件
'OtherResources' => ['OtherResources/**/*.png'] // 遞歸OtherResources文件夾下的所有以.png結(jié)尾的圖片
}
以上方式會(huì)生成多個(gè).bundle文件 當(dāng)然也可以一個(gè).bundle
spec.resource_bundles = {
'MyLibrary' => [''Resources/*.{png,xib}', 'Resources/source'], // Resources/source文件夾下的所有內(nèi)容包括子文件夾 和 Resources文件夾下的所有以.png結(jié)尾的圖片
}
訪問(wèn)bundle
由于 iOS 8 Dynamic Frameworks 特性的引入,CocoaPods 能幫你打包 framework 了
0.36 版的 release note很詳細(xì)地說(shuō)明了加入 framework 特性所帶來(lái)的變化。一個(gè)顯著區(qū)別就是當(dāng)你的 pod 庫(kù)以 framework 形式被使用時(shí),你的資源不是被拷貝到 mainBundle 下,而是被放到 pod 的最終產(chǎn)物—— framework 里。此時(shí),你必須保證自己在訪問(wèn)這個(gè) framework 的 bundle,而不是 client target 的。
上面這段代碼可以返回某個(gè) class 對(duì)應(yīng)的 bundle 對(duì)象。具體的,
[NSBundle bundleForClass:<#ClassFromPodspec#>]
- 如果你的 pod 以 framework 形式被鏈接,那么返回這個(gè) framework 的 bundle 即 framework 的 bundle 根目錄。
- 如果以靜態(tài)庫(kù)(.a)的形式被鏈接,那么返回 client target 的 bundle,即 mainBundle。
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
return [bundle URLForResource:@"MyLibrary" withExtension:@"bundle"];
先拿到最外面的 bundle。 對(duì) framework 鏈接方式來(lái)說(shuō)就是 framework 的 bundle 根目錄,對(duì)靜態(tài)庫(kù)鏈接方式來(lái)說(shuō)就是 target client 的 main bundle,然后再去找下面名為 MyLibrary 的 bundle 對(duì)象。
如果想拿到xxx.bundle里的對(duì)象 比如 xxx.bundle/source/main.jsbundle
[[NSBundle bundleForClass:[self class]] URLForResource:@"main" withExtension:@"jsbundle" subdirectory:@"xxx.bundle/source"];
圖片資源
- 訪問(wèn)主工程里的圖片 如下方式即可
[UIImage imageNamed:name]
這種方式 是否可訪問(wèn)main.bundle里文件夾下的圖片 ?
- 訪問(wèn)framework里bundle或某個(gè)bundle的圖片資源 如下方式即可
[UIImage imageNamed:name inBundle:bundle compatibleWithTraitCollection:nil]
注意:+ imageNamed:inBundle:compatibleWithTraitCollection: 這個(gè)方法 iOS 8 才加入的,之前可以如下
[UIImage imageWithContentsOfFile:[bundle pathForResource:name ofType:@"png"]];