How to set default localization for iOS app

后端 未结 6 1101
孤城傲影
孤城傲影 2021-02-07 01:51

I\'m developing app for Russian-speaking people. A lot of countries near Russia have the second language - Russian. My app has two localizations: Russian and English. And I need

6条回答
  •  半阙折子戏
    2021-02-07 02:00

    As eofster said you should set AppleLanguages key in NSUserDefaults to array of languages with desired order, but in order to work at first lunch you should do it very early, even earlier than applicationWillLunchWithOptions:

    As for me this solution works great and has advantage on using NSLocalizedStringFromTableInBundle because it works with storyboards and nibs as well.

    Here is step by step solution on Swift language.

    1. Make subclass of UIApplication as described here: Subclass UIApplication with Swift

    2. Second override init method of you UIApplication subclass to substitute list of preferred languages on your own.

      override init() {
          if let languages = NSUserDefaults.standardUserDefaults().objectForKey("AppleLanguages") as? [String],
              let language = languages.first where !language.hasPrefix("en")
          {
              NSUserDefaults.standardUserDefaults().setObject(["ru", "en"], forKey: "AppleLanguages")
          }
      
          super.init()
      }
      

      Swift 4:

      override init() {
      if let languages = UserDefaults.standard.object(forKey: "AppleLanguages") as? [String],
          let language = languages.first(where:{!$0.hasPrefix("en")})
      {
          UserDefaults.standard.set(["ru", "en"], forKey: "AppleLanguages")
      }
      
      super.init()
      

      }

    3. That's all. If first preferred language is not English you'll substitute list with Russian as first language.

    P.S. If you're doing not only localization, but internationalization don't forget to check locale which is used by date pickers, date formatters, number formatters, etc.

提交回复
热议问题