简体   繁体   English

Swift 2.0:NSBundle始终返回nil

[英]Swift 2.0 : NSBundle always returns nil

I'm implementing this git - NSDate-TimeAgo 我正在实现此git- NSDate-TimeAgo

It has swift extension inside. 它内部有快速扩展。 I have dragged and drop the Bundle that the git supply into my app - NSDateTimeAgo.bundle 我已经将git提供的Bundle拖放到我的应用程序中NSDateTimeAgo.bundle

In the extension file im trying to get this file path , but it always return nil SWIFT 2.0 在扩展文件中,im试图获取此文件路径,但始终返回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? 有什么建议么?

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 ): 查看实际代码的功能(在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. 只需安装NSDate + Extension.swift和捆绑软件,然后停止。 Don't change the code - all you're doing is breaking it. 不要更改代码-您要做的就是破坏它。

In case the accepted haven't worked - found solution - 万一被接受的方法无效-找到了解决方案-

  guard let resourcePath = NSBundle.mainBundle().resourcePath else {
        return ""
    }

    let path = NSURL(fileURLWithPath:resourcePath).URLByAppendingPathComponent("NSDateTimeAgo.bundle")
    guard let bundle = NSBundle(URL: path) else {
        return ""
    }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM