Reputation: 7603
I set the language of the simulator to French. To check the language code, I used a couple of solutions:
let lang = NSLocale.autoupdatingCurrent.languageCode
print(lang)
let pre = Locale.preferredLanguages[0]
print(pre)
The result are:
Optional("en")
fr-US
What I expected to get is:
fr
How can I achieve that?
Upvotes: 1
Views: 958
Reputation: 7269
Try below code,
let requiredString = pre.components(separatedBy: "-").first ?? pre //fr
/*if pre.contains("-"), then requiredString = before("-") else requiredString = pre*/
Upvotes: 4
Reputation: 608
print(Locale.components(fromIdentifier: Locale.preferredLanguages[0])["kCFLocaleLanguageCodeKey"]!)
this will print language code only.
Upvotes: 2
Reputation: 2099
If you want the Language instead of the Language_Region, then I suggest to take the sub string before the _ from the string to neglect the Region.
(If the string contains no _ then take the entire string since it doesn't contain the region in it)
Upvotes: 1