The problem
Yesterday I stumbled upon a problem when I loaded a xib file within my development pod.
I checked StackOverflow and found a few threads with the same issue:
- http://stackoverflow.com/questions/23835052/load-image-from-cocoapods-resource-bundle
- http://stackoverflow.com/questions/25433110/how-do-i-load-a-xib-file-from-my-cocoapod
I used the following code inside my Pod library to load a xib file which was also located in the same directory as my Pod source code.
let nib = UINib(nibName: "MyNib", bundle: nil)
When you add this Pod to your project to test, you’ll get a runtime error telling you that the nib can’t be found. It seems that the xib files you provide aren’t copied over.
How to load bundle resources in Cocoapods
So I checked my Podspec file and the CocoaPod spec reference guide, and saw you have an option to create resource_bundles. All you need to do is add the assets you want to be added to the bundle. They key you specify will be the name of the bundle.
So I changed my podspec file to copy all xibs in my Pod project
s.resource_bundles = { 'MyCustomPod' => [ 'Pod/**/*.xib' ] }
This code will add all the xib files inside the Pod directory (the ** will recursively check all subfolders of the Pod directory) to a bundle named MyCustomPod.
Having added this, it’s a good thing to run pod install again.
In your Pod code you can now add the following code to load the xib file from the bundle.
let podBundle = NSBundle(forClass: self.classForCoder) if let bundleURL = podBundle.URLForResource("MyCustomPod", withExtension: "bundle") { if let bundle = NSBundle(URL: bundleURL) { let cellNib = UINib(nibName: classNameToLoad, bundle: bundle) self.collectionView!.registerNib(cellNib, forCellWithReuseIdentifier: classNameToLoad) }else { assertionFailure("Could not load the bundle") } }else { assertionFailure("Could not create a path to the bundle") }