Search code examples
iosswiftnsbundle

Get file path from a NSBundle which is not the mainBundle


I'm trying to get a pathForResource for a plist file, when the file was in the mainBundle it was easy, i used:

let path = NSBundle.mainBundle().pathForResource("Settings", ofType: "plist")

But now i moved the settings file to another bundle and i don't know how to get it. I tried to use forClass and allBundles but i'm a swift rookie and didn't managed to make it work. Also coulden't find the solution over the web. It seems all the NSBundle usages examples is only for mainBundle


Solution

  • If you don't know which bundle has your resource you could loop through all of them:

    let bundles = NSBundle.allBundles()
    
    var path : String?
    var myBundle : NSBundle?
    
    for bundle in bundles {
        if let resourcePath = (bundle as! NSBundle).pathForResource("Settings", ofType: "plist") {
            path = resourcePath
            myBundle = bundle
            break
        }
    }
    

    On the other hand, if you do have the path or the identifier of your bundle you could use:

    let bundle = NSBundle(path: "the-bundle-path")
    
    or
    
    let bundle = NSBundle(identifier: "bundle-identifier")
    

    This has nothing to do with the level of your Swift programming knowledge, rather with the interface NSBundle exposes. You should check the docs out to see if they can help you.