Search code examples
iosswiftnullswift2nsbundle

Swift 2.0 : NSBundle always returns nil


I'm implementing this git - NSDate-TimeAgo

It has swift extension inside. I have dragged and drop the Bundle that the git supply into my app - NSDateTimeAgo.bundle

In the extension file im trying to get this file path , but it always return nil SWIFT 2.0

func NSDateTimeAgoLocalizedStrings(key: String) -> String {

let resourcePath = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let path = resourcePath.URLByAppendingPathComponent("NSDateTimeAgo.bundle")
let bundle = NSBundle(URL: path)
print(bundle) -> **nil**

return NSLocalizedString(key, tableName: "NSDateTimeAgo", bundle: bundle!, comment: "")
}

Any suggestions?


Solution

  • The bundle has to be copied into your resources folder, not into the top level of your app bundle.

    This line is just wrong:

    let resourcePath = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
    

    The bundle is not in your documents directory. It's in your app. Look at what the actual code does (in NSDate+Extension.swift):

    func NSDateTimeAgoLocalizedStrings(key: String) -> String {
    
        // LOOK!!!!
        let resourcePath = NSBundle.mainBundle().resourcePath
        let path = resourcePath?.stringByAppendingPathComponent("NSDateTimeAgo.bundle")
        let bundle = NSBundle(path: path!)
    
        return NSLocalizedString(key, tableName: "NSDateTimeAgo", bundle: bundle!, comment: "")
    }
    

    Basically you should just let it do this. Don't mess with the bundle yourself. Just install NSDate+Extension.swift and the bundle, and stop. Don't change the code - all you're doing is breaking it.