2017-06-17 102 views
0

我想從我的項目中獲得本地化的JSON文件。使用下面的代碼,一切在模擬器上都很好,但不是在真實設備上。文件只在模擬器上加載而不是在真實設備上(Swift 3)

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

我認爲你使用的是錯誤的方法。假設你爲每個支持的語言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")    } 
     } 

    } 
+0

iPhone有這個網址:文件:/// VAR /瓶/包/Application/F2BC4739-F484-4435-AAA6-4BA5E0724F08/Remember_The_Bill.app/document.json –

+0

我知道這是錯誤的,但我不知道如何解決它 –

相關問題