【问题标题】:Loading JSON failed after adding localization to it Swift 3在 Swift 3 中添加本地化后加载 JSON 失败
【发布时间】:2017-06-11 12:59:09
【问题描述】:

嘿,我的应用中有一个用于预设数据的 JSON。通常我是这样加载数据的:

        if let path = Bundle.main.path(forResource: "document", ofType: "json")

    {

        let jsonData = try NSData(contentsOfFile: path, options: NSData.ReadingOptions.mappedIfSafe)
  ... }

但是在我像这样本地化 document.json 文件之后:

不会加载任何数据。 有人知道如何获取本地化数据吗?

【问题讨论】:

    标签: ios json swift xcode swift3


    【解决方案1】:

    由于本地化,本地化文件位于 lproj 文件夹中,而不是位于 mein Resources 文件夹中。

    一种解决方案是使用支持的语言创建一个数组,并从当前语言环境中获取当前语言。如果当前语言与其中一种支持的语言不匹配,请回退到默认语言。

    let supportedLocalizations = ["en", "de"]
    
    let currentLanguage : String
    if let locale = Locale.current.languageCode, supportedLocalizations.contains(locale) {
        currentLanguage = locale
    } else {
        currentLanguage = Bundle.main.object(forInfoDictionaryKey: "CFBundleDevelopmentRegion") as! String
    }
    let url = Bundle.main.url(forResource: "document", withExtension: "json", subdirectory: nil, localization: currentLanguage)!
    let jsonData = try! Data(contentsOf: url)
    

    如果强制展开的部件崩溃,则表明存在设计错误。所有文件都应该在运行时存在。

    【讨论】:

      猜你喜欢
      • 2017-10-29
      • 2016-08-26
      • 1970-01-01
      • 2019-06-30
      • 1970-01-01
      • 1970-01-01
      • 2012-01-16
      • 2018-01-29
      • 1970-01-01
      相关资源
      最近更新 更多