0

How do I grab all of the checked languages for Localization programmatically in Swift with Xcode 12?

I want to have these languages in an array that I can display as a picker view so the user can seamlessly change the language without having to change the language of their device. I want to avoid hard coding this.

Screenshot of the Localization check boxes in Xcode from my .strings file

1
  • Maybe FileManager.default.contentsOfDirectory(atPath: Bundle.main.bundlePath).filter { $0.hasSuffix(".lproj") } might be helpful... Commented Jul 13, 2021 at 16:44

1 Answer 1

2

This might do the trick:

func localizations() -> [String] {
    guard let contentsURLs = try? FileManager.default.contentsOfDirectory(at: Bundle.main.bundleURL, includingPropertiesForKeys: nil) else { return [] }
    let identifiers = contentsURLs.compactMap { anURL -> String? in
        guard anURL.pathExtension == "lproj" else { return nil }
        return anURL.deletingPathExtension().lastPathComponent
    }

    let humanReadableNames = identifiers.compactMap { anIdentifier in
        return Locale.current.localizedString(forIdentifier: anIdentifier)?.localizedCapitalized
    }

    return humanReadableNames
}

I even transformed them into human readable languages names, instead of having for instance "zh-Hans" for "Chinese (Simplified)". Of course, if you handle yourself your locale, your might want to use a different Locale.current, but you get the idea...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.