簡體   English   中英

Swift 2.0:NSBundle始終返回nil

[英]Swift 2.0 : NSBundle always returns nil

我正在實現此git- NSDate-TimeAgo

它內部有快速擴展。 我已經將git提供的Bundle拖放到我的應用程序中NSDateTimeAgo.bundle

在擴展文件中,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: "")
}

有什么建議么?

捆綁軟件必須復制到資源文件夾中,而不是復制到應用捆綁軟件的頂層。

這行是錯誤的:

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

該捆綁包不在您的文檔目錄中。 在您的應用中。 查看實際代碼的功能(在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: "")
}

基本上,您應該讓它執行此操作。 不要自己弄亂捆綁包。 只需安裝NSDate + Extension.swift和捆綁軟件,然后停止。 不要更改代碼-您要做的就是破壞它。

萬一被接受的方法無效-找到了解決方案-

  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