Simon McLoughlin
Simon McLoughlin

Reputation: 8465

Swift framework can't get file in another bundle

I'm up-skilling on swift. I'm writing a framework that will depend on a file that will not be part of the framework. It will be created by the app that imports the framework.

It works fine when running on the simulator but the live rendering in interface builder craps out because it can't find the file. I've done the same thing previously in Objective-c and I know the solution is that the interface builder is using a different bundle. The solution was to use:

[[NSBundle bundleForClass:[self class]] pathForResource:<fileName> ofType:<fileType>]

I've searched online and I believe the equivalent in swift is:

let path:String? = NSBundle(forClass: self.dynamicType).pathForResource(<fileName>, ofType: <fileType>)

however it always returns nil inside the live rendering. While:

let path:String? = NSBundle.mainBundle().pathForResource(<filename>, ofType: <fileType>)

works fine in the simulator, meaning the file is clearly there and part of the finished app. Anyone have any idea why this might be? is there a setting somewhere i'm missing also?

Upvotes: 1

Views: 1426

Answers (1)

jvoll
jvoll

Reputation: 999

In Swift the code looks like this:

return NSBundle.init(forClass: <ClassName>.self).pathForResource(<FileName>, ofType: <FileType>)

for example, to get localization resources in Arabic from another bundle your code would look like this:

return NSBundle.init(forClass: <ClassName>.self).pathForResource("ar", ofType: "lproj")

I think part of your problem might be that you are trying to hit another bundle but you are accessing the bundle for the current class with your call to [[NSBundle bundleForClass:[self class]].

I haven't written much objective-C but I suspect you will be able to translate this on my behalf.

Upvotes: 1

Related Questions