Load assets from bundle resources in Cocoapods

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:

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.

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

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.

 

  • Glen Ruhl

    Thank you ever so much sir. You don’t know just how long I was trying to find where the name of my Cocoapods bundle was being defined.

  • idStar

    This is helpful. Leaving xib files alongside classes doesn’t generate an error when validating podspecs the way leaving Storyboard files in there does; so this is handy to know. To clarify, when you recommend running ‘pod install’ after this update, you’re talking about doing so in the project that pulls in the cocoapod that you have defined and adjusted the podspec for, correct?

  • biocross

    thanks for this! 🙂

  • Didier (Logiq)

    Tried your code and all I get is “Could not load the bundle”. I can see my bundle located in Pods/Products as “MyBundle.bundle” but for some reason it can’t create path. Any suggestions? Im trying to load Quicksand font located in the bundle

  • chanricle

    I just get bundle description: NSBundle (not yet loaded)

    (not yet loaded)!! And this bundle invalid sure. How to fix this issue?

  • Muhammad Youshea Khan

    Got the bundle path, also got the storyboard path that i want to use but when i initialise the storyboard using the bundle i got from the above code it says not storyboard with the name(my storyboard name found) in the bundle

    ERROR :

    Could not find a storyboard named ‘storyboard_name’ in bundle NSBundle (not yet loaded)

  • FG

    This worked well as hell!