【问题标题】:How to read Localizable.strings in the app如何在应用程序中读取 Localizable.strings
【发布时间】:2020-05-30 06:44:22
【问题描述】:

我有多种语言的 Localizable.strings 文件。

我想在应用程序中逐行阅读当前的 Localizable.strings 以提供翻译帮助。

        let bpath:String = Bundle.main.path(forResource: "es", ofType: "lproj")! as String

        if let filepath = Bundle.main.path(forResource: bpath + "/Localizable.strings", ofType: nil) {
            do {
                let contents = try String(contentsOfFile: filepath)
                print(contents)
            } catch {
                // contents could not be loaded
                let alert = UIAlertController(title: "Erreur".localized, message: "Fichier \(bpath + "/Localizable.strings") non accessible".localized, preferredStyle: .alert)

                alert.addAction(UIAlertAction.init(title: "Ok".localized, style: .cancel, handler: nil))
                self.present(alert, animated: true, completion: nil)
            }
        } else {
            // example.txt not found!
            let alert = UIAlertController(title: "Erreur".localized, message: "Fichier \(bpath + "/Localizable.strings") non trouvé".localized, preferredStyle: .alert)

            alert.addAction(UIAlertAction.init(title: "Ok".localized, style: .cancel, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }

找不到文件。

PS:这段代码完美运行,但目标是读取所有“键”。

    let bpath:String = Bundle.main.path(forResource: "es", ofType: "lproj")! as String
    let bundle = Bundle(path: bpath as String)
    let thisWord="Erreur"
    let ourWord=NSLocalizedString(thisWord, bundle: bundle!, comment: "")

【问题讨论】:

  • 使用菜单编辑器 > 导出本地化...
  • 谢谢,但这不是目标。我想从应用程序访问 localizable.strings 文件。

标签: swift file-io localizable.strings


【解决方案1】:

使用以下方法查找路径:

let filepath = Bundle.main.path(forResource: "Localizable", 
                                ofType: "strings", inDirectory: "es.lproj")

【讨论】:

  • 谢谢,但也许你可以帮我多一点……现在我可以访问该文件,但我无法加载它。我有一个错误 do { let contents = try String(contentsOfFile: filepath) print(contents) } catch { // 无法加载内容 }
  • @PascalS,你应该指定编码,如果 Localizable.strings 生成/准备正确,它应该是 UTF-16,所以String(contentsOfFile: filepath, encoding: .utf16)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-13
  • 1970-01-01
  • 1970-01-01
  • 2022-06-10
  • 1970-01-01
  • 2021-12-07
  • 2016-10-25
相关资源
最近更新 更多