How to get the OS language and language?

My application changes the language at runtime and advises the user to restart the application. I do it like this:

    typealias LanguageLocaleType = (language: String?, locale: String?, title: String)

    let elements: [LanguageLocaleType] = [
        (nil, nil, "System Default"),
        ("en", "en_US", "English"),
        ("ar", "ar_SA", "Arabic"),
    ]

    //...func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)...

    let element = elements[indexPath.row]

    guard let language = element.language else {
        // How to really reset app back to OS language/locale???
        UserDefaults.standard.removeObject(forKey: "AppleLanguages")
        UserDefaults.standard.removeObject(forKey: "AppleLocale")
        return
    }

    UserDefaults.standard.set([language], forKey: "AppleLanguages")

    if let locale = element.locale, !locale.isEmpty,
        Locale.current.identifier != locale,
        !Locale.current.identifier.hasPrefix("\(language)_") {
            UserDefaults.standard.set(locale, forKey: "AppleLocale")
    }

I want to offer to install the languages ​​in the list with the right choice, one of which is suggested to him to set the language back to System Default. However, there is no way to find the OS language and the level of language that I could find. Since after I got confused with the setup UserDefaults, Bundle.main.preferredLocalizationsit is not reliable and does not comply with the system standard (event when I delete the key from User Default).

Is there a way to get the language and locale at the OS level instead of the application level?

+6
source share
4 answers

OS, .

    let language  = NSLocale.preferredLanguages[0]

, , fooobar.com/questions/28221/...

+4

Cocoa pods.

:

pod 'Localize-Swift', '~> 1.7'

:

pod install

, Localizable.strings, Localizable.strings(), .

"LD" = "Loading ...";
"CAMP" = "Campus";
"MAP" = "MAP";

TAG, - .

ViewController .

:

let progressHUD = ProgressHUD(text: "LD".localized())
let progressHUD = ProgressHUD(text: "CAMP".localized())
let progressHUD = ProgressHUD(text: "MAP".localized())

.

, .

+1

, , , - , Bundle . .

, Bundle, , , Core Data, XML (.plist). didFinishWithOptions, , , , , ( , , , ). , NSLocale, , .

1: , , Apple-Tolerated. 2: OP , , , Apple . , - NSLocale , Swift, , . , : (

+1

All Articles