Search code examples
swiftfile-iolocalizable.strings

How to read Localizable.strings in the app


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: "")

Solution

  • Use the following to find a path:

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