2016-02-29 259 views
10

我一直在爲如何加載cocoapods resource_bundle中的資源而苦苦掙扎。如何在cocoapods中加載資源resource_bundle

以下是我在.podspecs文件中的內容。

s.source_files = 'XDCoreLib/Pod/Classes/**/*' 
s.resource_bundles = { 
'XDCoreLib' => ['XDCoreLib/Pod/Resources/**/*.{png,storyboard}'] 
} 

這就是我想要從主項目中做的。

let bundle = NSBundle(forClass: XDWebViewController.self) 
let image = UIImage(named: "ic_arrow_back", inBundle: bundle, compatibleWithTraitCollection: nil) 
print(image) 

我看過XDCoreLib.bundle中的圖片,但返回nil。

+0

這樣不行,只是複製這些資源到你的項目,因爲這些資源在吊艙可隨時更新/刪除。 –

+1

這個吊艙由我們自己維護。項目規模越來越大,我們希望將每個模塊分開。 –

回答

16

我在一段時間內遇到了類似的問題。資源包實際上是一個與您的代碼所在位置不同的捆綁包。請嘗試以下操作:

let frameworkBundle = NSBundle(forClass: XDWebViewController.self) 
let bundleURL = frameworkBundle.resourceURL?.URLByAppendingPathComponent("XDCoreLib.bundle") 
let resourceBundle = NSBundle(URL: bundleURL!) 
let image = UIImage(named: "ic_arrow_back", inBundle: resourceBundle, compatibleWithTraitCollection: nil) 
print(image) 
+0

太棒了!我錯過了「URLByAppending」,謝謝 –

+0

@ Quaid XDWebViewController.self在第一行什麼是 – Siddh

+0

@Siddh'XDWebViewController.self'應該是一個類中的類。 –

0

有趣的事情是,當你需要做的是在同樣的cocoapod庫 我面對我的莢使用的廈門國際銀行和的plist文件時的源文件。

這是在下一個方法解決。加載廈門國際銀行文件的示例:

let bundle = Bundle(for: self.classForCoder) 
let viewController = CocoapodViewController(nibName: "CocoapodViewController", bundle: bundle) 
1

我不認爲任何其他的答案中所描述的Podspec的關係。軟件包URL使用該容器的名稱,然後使用.bundle來查找資源包。此方法適用於資產目錄,以訪問吊艙內外的吊艙圖像。

Podspec

Pod::Spec.new do |s| 
    s.name    = 'PodName' 
    s.resource_bundles = { 
    'ResourceBundleName' => ['path/to/resources/*/**'] 
    } 
end 

目標C

// grab bundle using `Class` in pod source (`self`, in this case) 
NSBundle *bundle = [NSBundle bundleForClass:self.classForCoder]; 
NSURL *bundleURL = [[bundle resourceURL] URLByAppendingPathComponent:@"PodName.bundle"]; 
NSBundle *resourceBundle = [NSBundle bundleWithURL:bundleURL]; 
UIImage *podImage = [UIImage imageNamed:@"image_name" inBundle:resourceBundle compatibleWithTraitCollection:nil]; 

夫特

參見this answer

0

只是爲了記錄:我想打開存儲在CocoaPods庫中的類別的NIB。當然[self classForCoder]回到UIKit(因爲類別),所以上面的方法不起作用。

我使用一些硬編碼的路徑,解決了這個問題:

NSURL *bundleURL = [[[NSBundle mainBundle] resourceURL] URLByAppendingPathComponent:@"Frameworks/MyCocoaPodLibraryName.framework"]; 
NSBundle *podBundle = [NSBundle bundleWithURL:bundleURL]; 

CustomView *customView = [[podBundle loadNibNamed:@"CustomView" owner:self options:nil] firstObject]; 
2

這會在你的代碼工作

.podspec除了添加s.resourcess.resource_bundlespod install後)

s.resources = 'XDCoreLib/Pod/Resources/**/*.{png,storyboard}' 

然後,它很容易:

let image = UIImage(named: "image_name.png", in: Bundle(for: type(of: self)), compatibleWith: nil) 
0

您可以通過選擇Pods項目,選擇所需的目標並確保您位於General選項卡上來檢查Bundle的ID。

enter image description here

然後在代碼中,你可以加載說在波德圖像,像這樣:

backgroundImageView.image = UIImage(named: "business_fellas", in: Bundle(identifier: "org.cocoapods.StandardLibrary3-0"), compatibleWith: nil)