nelson PARRILLA
nelson PARRILLA

Reputation: 703

List available languages of an iOS app in swift

What is the easiest way to list available languages of an iOS app in Swift ?

Here is what I would like to do :

let availableLanguages: [String] = ?
let currentLanguage = Locale.current.languageCode

if !availableLanguages.contains(currentLanguage) {
    UserDefaults.standard.set("en", forKey: "AppleLanguage")
}

I would like to replace the "?" with the cleanest solution.

Edit

By available, I mean Language for which the app has a Localizable.string

Upvotes: 1

Views: 3595

Answers (3)

Yonathan Goriachnick
Yonathan Goriachnick

Reputation: 201

The simplest way to list all Localizable files that are included in the bundle you simply need to call:

Bundle.main.localizations

According to the docs in the swift source code it will return a:

list of language names this bundle appears to be localized to

Upvotes: 7

timbre timbre
timbre timbre

Reputation: 13970

Based on your clarification, what you need is Bundle's localizations. Directly answering your question, you are looking for localizations:

A list of all the localizations contained in the bundle.

But you can simplify it with preferredLocalizations from the bundle. And you don't really need to check current locale, that list is already ordered:

The strings are ordered according to the user's language preferences and available localizations.

So top of the list is best match for current user locale:

let preferredLanguages = Bundle.main.preferredLocalizations as [String]
guard preferredLanguages.count > 0 else {
   // no localizations case
   return
}

UserDefaults.standard.set(preferredLanguages[0], forKey: "AppleLanguage")

Also look at preferredLocalizations(from:forPreferences:) if you need more precise customizations

Upvotes: 5

Zack117
Zack117

Reputation: 1075

At my current company, we need to support different locals for Canada and use an enum for that. Depending on where you need to access this enum, I would put it in some global object or a protocol class. Let me know if that makes sense if your new at IOS. What your doing may be easiest to understand, but has some draw backs.

this doc should clear everything up: https://docs.swift.org/swift-book/LanguageGuide/Enumerations.html

Upvotes: 0

Related Questions