I'm trying to create a framework that keeps some common code I use around in my projects. I found online tutorials and managed to create a framework but I still have one problem related to resources (xibs, images, etc).
Let's say I have a MainViewController.xib
which has a UIImageView
using a test.png
. All these are in my framework package.
When I use the framework in another project, I add it to the "Copy Bundle Resources" build phase. The problem is that the xib is only accessible using a path like dummy.framework/Resources/MainViewController.xib
and the UIImageView
inside can't load test.png
.
It seems that the UIImageView will try to load the png from the root of the bundle, and not from the relative folder where the xib is also stored.
Has anybody managed to create a framework with code and resources and use it in another project?
I created a framework target and to access images inside its asset catalog I did the following:
I don't manually manage frameworks anymore but use and recommend CocoaPods instead.
Original answer:
Inspired by this script, add this to your target to copy the resources to your app:
You could also just drag the framework to your Copy Resources step, but then you'll be adding unnecessary headers and compiled code as well.
Edit
To use these resources from IB, for instance a png file, replace:
by:
It will preview a broken image icon but will work when running.
Load a Nib from code:
Finally you can add these methods in a NSBundle category to ease access to Nib resources that my be in your main bundle or in MYFrameworkResources.bundle:
It will first look into your application bundle and then in MYFrameworkResources.bundle, etc.
Basic frameworks do not include most kinds of resources, to include resources use this "fake" framework library
You end up with a .embeddedframework folder which contains the actual framework, but also includes any resources which you add to the Copy Bundle Resources build phase. Ive used it to include xibs, core data models, images, and plists
As of Xcode 7 we can now use Asset Catalogs. In my experiments I've found that u can reference files in the same workspace bit different projects removing the need to micro manage assets in build phases or worrying about targets.
In order to load an image from a dynamic framework in Swift 3:
UIImage(named: "name", in: Bundle(for: type(of: self)), compatibleWith: nil)
Short answer: you can't.
When you compile the app, the bundle is generated with the resources of the "main" project, ignoring the resources in linked frameworks. This includes images, xib's, plist's, etc. (anything that isn't a source file)
What you need to do is add those resources to your main project so that they are available for use inside your application, not the happiest way around it but it'll work.