文件仅在模拟器上加载而不在真实设备上加载(Swift 3)

时间:2017-06-17 12:01:14

标签: ios xcode file swift3 localization

我正在尝试从我的项目中获取本地化的JSON文件。使用以下代码,一切都在模拟器上运行良好,但不适用于真实设备。

 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)

有谁知道原因?

1 个答案:

答案 0 :(得分:0)

我认为你使用了错误的方法。假设你有一个支持每种语言的json文档,为什么不把这个语言加到文件名中,然后像这样加载:

var json : NSDictionary!
let fileName = "document_" + currentLanguage
if let url = Bundle.main.url(forResource: fileName,                        
          withExtension: "json") {
    if let data = NSData(contentsOf: url) {
        do {
            json = try JSONSerialization.jsonObject(with: data as
                    Data, options: .allowFragments) as? NSDictionary
        } catch {
            print("Unable to parse  \(fileName).json")             }
        }

    }