1

I have Localizable.strings files for many languages.

I would like to read the current Localizable.strings line by line in the app to make a translation help.

        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)
        }

It don't find the file.

PS : This code works perfectly, but the goal is to read all "keys".

    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: "")
PascalS
  • 89
  • 1
  • 10

1 Answers1

1

Use the following to find a path:

let filepath = Bundle.main.path(forResource: "Localizable", 
                                ofType: "strings", inDirectory: "es.lproj")
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • thanks, but may be you could help me a little bit more... now I access to the file but I can't load it. I have an error do { let contents = try String(contentsOfFile: filepath) print(contents) } catch { // contents could not be loaded } – PascalS May 30 '20 at 18:54
  • 1
    @PascalS, you should specify encodings, if Localizable.strings generated/prepared correctly it should be UTF-16, so `String(contentsOfFile: filepath, encoding: .utf16)` – Asperi May 30 '20 at 19:01