topgun
topgun

Reputation: 2583

How to load resources from external framework

I have build an external framework, and I am trying to utilize some images which are in the resource directory of the framework. The framework is not being copied within the application but rather just referenced to it. How can I utilize UIImage accordingly from xyz.framework resource folder?

Thanks

Upvotes: 17

Views: 13876

Answers (5)

rpstw
rpstw

Reputation: 1712

Use bundle identifier to locate your framework.

This requires the frameworks's "MACH-O Type" to be "Dynamic Library" and configured as "Embed & Sign".

NSBundle *bundle = [NSBundle bundleWithIdentifier:@"com.example.App.ExampleFramework"];
NSURL *url = [URLForResource:@"resource" withExtension:@"txt"];
// load the contents with this file url

Upvotes: 1

bojan
bojan

Reputation: 971

Swift 4/5:

let bundle = Bundle(for: type(of: self))
// let bundle = Bundle(for: ClassOfInterest.self)) // or by pointing to class of interest
let path = bundle.path(forResource: "filename", ofType: "json")!
let url = URL(fileURLWithPath: path)
let data = try! Data(contentsOf: url)

This is from inside framework / unit tests, in production code you don't want to force try and force unwrap.

Upvotes: 4

Ivan Mir
Ivan Mir

Reputation: 1239

Swift 3:

let bundle = Bundle(for: SomeFrameworkClass.self as AnyClass)

if let path = bundle.path(forResource: "test", ofType: "png") {
    if let image = UIImage(contentsOfFile: path) {
        // do stuff
    }
}

Upvotes: 4

DShah
DShah

Reputation: 9876

You can refer to Framework resources as follows :

[[NSBundle mainBundle] pathForResource:@"FI.framework/Resources/FileName"
                                ofType:@"fileExtension"];

Note, here FI is your framework name.

Ref. Link : http://db-in.com/blog/2011/07/universal-framework-iphone-ios-2-0/

Upvotes: 4

mamackenzie
mamackenzie

Reputation: 1166

What you need to do is load the bundle for the framework, and then access the resources using the NSBundle object.

For example, if there is a framework that defines a class "FrameworkClass", we can do:

NSBundle *frameworkBundle = [NSBundle bundleForClass:[FrameworkClass class]];
NSString *resourcePath = [frameworkBundle pathForResource:@"an_image" ofType:@"jpeg"];
UIImage *image = [UIImage imageWithContentsOfFile:resourcePath];

That should more or less do what you want.

Upvotes: 37

Related Questions