Localize iOS 14 dynamic widget configuration

前端 未结 2 673
-上瘾入骨i
-上瘾入骨i 2021-01-21 04:03

I am trying to load different configuration for the widgets depending on the app language, but when I use something like:

Locale.preferredLanguages
Bundle.main.pr         


        
2条回答
  •  抹茶落季
    2021-01-21 04:50

    There is a simple solution:

    1. Add AppGroups capability for both Parent App and the widget.

    2. Create simple UserDefaults

       let SharedGroupName = "group.pl.blueworld.fieldservice"
       let PreferredLanguageKey = "PreferredLanguageKey"
       extension UserDefaults {
           static let shared = UserDefaults(suiteName: SharedGroupName)!
       }
      
    3. Save current language in shared UserDefaults.

       func applicationDidBecomeActive(_ application: UIApplication) {
           UserDefaults.shared.setValue(Locale.preferredLanguages[0].prefix(2), forKey: PreferredLanguageKey)
       }
      
    4. Access value inside Widget View:

       struct MyView: View {
           var language: String {
               return UserDefaults.shared.string(forKey: PreferredLanguageKey) ?? "en"
           }
       }
      

提交回复
热议问题