我正在尝试从我的项目中获取本地化的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)
有谁知道原因?
答案 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") }
}
}