How to Retrieve a File/Resource in a iOS Framework Bundle from a Main Program

How to read resources files within a framework?

Instead of calling +[NSBundle mainBundle], call either +[NSBundle bundleWithIdentifier:] or +[NSBundle bundleForClass:]. The former takes an NSString argument of the framework's indentifier; the latter takes a Class argument of a class provided by the framework. Then, you can call the usual NSBundle paths as necessary.

Full documentation can be found here.

Path to bundle of iOS framework

Use Bundle(for:Type):

let bundle = Bundle(for: type(of: self))
let path = bundle.path(forResource: filename, ofType: type)

or search the bundle by identifier (the frameworks bundle ID):

let bundle = Bundle(identifier: "com.myframework")

How to load resources from external framework

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.

How to access file included in app bundle in Swift?

Simply by searching in the app bundle for the resource

var filePath = NSBundle.mainBundle().URLForResource("file", withExtension: "txt")

However you can't write to it because it is in the app resources directory and you have to create it in the document directory to write to it

var documentsDirectory: NSURL?
var fileURL: NSURL?

documentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last!
fileURL = documentsDirectory!.URLByAppendingPathComponent("file.txt")

if (fileURL!.checkResourceIsReachableAndReturnError(nil)) {
print("file exist")
}else{
print("file doesnt exist")
NSData().writeToURL(fileURL!,atomically:true)
}

now you can access it from fileURL

EDIT - 28 August 2018

This is how to do it in Swift 4.2

var filePath = Bundle.main.url(forResource: "file", withExtension: "txt")

To create it in the document directory

if let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last {
let fileURL = documentsDirectory.appendingPathComponent("file.txt")
do {
if try fileURL.checkResourceIsReachable() {
print("file exist")
} else {
print("file doesnt exist")
do {
try Data().write(to: fileURL)
} catch {
print("an error happened while creating the file")
}
}
} catch {
print("an error happened while checking for the file")
}
}

Can't find resource from Bundle

  1. Click the target of project.
  2. Select the item of Build Phase.
  3. under Copy Bundle Resources check if your file is listed or not. If not
    listed add with the plus button.
    Sample Image


Related Topics



Leave a reply



Submit