1

I'm trying to get the current phone language in swift. I think I know how to do it...but I got wrong language. My app has 2 localizations already done (english and spanish). But I'll like to get the real iOS language, so I can say user, "We are preparing translation to Italian very soon", or something like that....

I'm on iOS 13.2.2 / XCode 11.2.1

I have tried many ways for doing so see the results I got for that code:

    print(NSLocale.current.languageCode as Any)
    print(Locale.current.languageCode as Any)
    print(Locale(identifier: Locale.current.identifier).identifier)
    print(Locale.preferredLanguages)
    print(NSLocale.preferredLanguages)
    print(Locale.current.regionCode as Any)
    print(NSLocale.preferredLanguages[0] )
    print(NSLocale.components(fromLocaleIdentifier:
        NSLocale.preferredLanguages.first!)[NSLocale.Key.languageCode.rawValue])

None of these give me correct result.

For example, setting iOS language to Italian in Settings -> General -> Languages and Zones -> iPhone Language -> Italian I got:

    print(NSLocale.current.languageCode as Any)
Optional("es")

    print(Locale.current.languageCode as Any)
Optional("es")

    print(Locale(identifier: Locale.current.identifier).identifier)
es_US

    print(Locale.preferredLanguages)
["es"]

    print(NSLocale.preferredLanguages)
["es"]

    print(Locale.current.regionCode as Any)
Optional("US")

    print(NSLocale.preferredLanguages[0] )
es

    print(NSLocale.components(fromLocaleIdentifier:NSLocale.preferredLanguages.first!)[NSLocale.Key.languageCode.rawValue])
Optional("es")

How can I do it to get "it".....

Thanks

2 Answers2

2

If to combine in one long call it is

NSLocale.components(fromLocaleIdentifier: 
   NSLocale.preferredLanguages.first!)[NSLocale.Key.languageCode.rawValue]

Initial output:

(lldb) e NSLocale.preferredLanguages
([String]) $R10 = 2 values {
  [0] = "it-US"
  [1] = "en"
}

Tested with Xcode 11.2 / iOS 13.2

PS. iPhone device language must be changed before application launch.

Asperi
  • 228,894
  • 20
  • 464
  • 690
0

Why don't you create a copy of your default language (let's assume it's English), mark it as Italian and add your phrase "We are preparing translation to Italian very soon"?

This way your app will "think" it supports Italian, but will actually display English texts.

This solution has some limitations though: If a user configures a given language hierarchy in his/hers device: Italian/Spanish/English, he/she would expect that due to lack of support of Italian language, Spanish would be used. Actually, app will use English (dressed up as Italian), so it may cause some confusion.