简体   繁体   中英

Set default language before the app starts for the first time in iOS/Swift

I wanna set another language as default when the app starts for the first time. iOS doesn't not have this language as an interface language, so my only way is to set it manually. I've found dozens of solutions on SO, and those that work, ONLY work in simulator and not on a real device. Here's what I've tried:

First of all, the way to set the app's language is:

UserDefaults.standard.set(["xx-XX", "yy-YY"], forKey: "AppleLanguages")

The thing is, that this needs the app to be restarted, while I want it to be set the first time the app starts . I've also tried:

UserDefaults.standard.register(defaults: ["AppleLanguages": ["xx-XX", "yy-YY"]])

and even calling UserDefaults.standard.synchronize() which in most cases is not needed at all.

And the places I've tried putting this code:

  1. application(:didFinishLaunchingWithOptions:)
  2. application init :|
  3. Subclassing UIApplication , creating main.swift and adding the above codes as top level statements

And in info.plist :

  1. Setting Localization native development region to xx-XX
  2. Setting the first element of Localizations to xx-XX

By the way, implementing custom localization is not an option at this point in time.

And what confuses me the most, is why such a feature works in simulator and not a real device.

EDIT: I even deleted the default english language, and adding English (World) again, so that there was no Development Language label beside it. Still didn't work.

On Xcode next from the Start Stop Buttons you can press the "projectName" -> Edit Scheme... -> Run -> Options and change in Application Language

在此输入图像描述

Well, there was not one single legitimate way to do it. So I had to use a nasty trick.

  1. Added a language that we're not using (in this case fr ) 在此输入图像描述
  2. In the process of creation, chose english (yy-YY as in my question) as the reference language (So that I wouldn't have to do any translation/localization again) 在此输入图像描述

At this point, my development language kicked in, and xx-XX (in this case fa-IR) was my default. And you know the rest, setting the AppleLanguages user default.

Again, this is not the best and a clean way to do it, and if you are early in the development process, go with a custom implementation of localizing your app, or use L10n-Swift . That is of course, if you can't stick with what iOS chooses for you based on the device locale selected by the user.

To make the default language as a particular one this following code works like a charm.(Swift 4.2)

let arr = NSArray(objects: "ja")
UserDefaults.standard.set(arr, forKey: "AppleLanguages")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM