Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Localize iOS 14 dynamic widget configuration

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.preferredLocalizations
Bundle.main.localizations

all of them are returning "en" only in IntentExtensionTarget.

here is an example where I am using the code:

extension IntentHandler: ReciterAndSurahIntentHandling {
    
    func provideSurahOptionsCollection(for intent: ReciterAndSurahIntent, with completion: @escaping (INObjectCollection<NSString>?, Error?) -> Void) {
        
        Locale.preferredLanguages
        Bundle.main.preferredLocalizations
        Bundle.main.localizations
        // All of them return "en" only, and I have multiple localization for the app.
    }
}
like image 632
FarouK Avatar asked Mar 02 '23 00:03

FarouK


2 Answers

You get EN only, because localization in description and widget names is based on device language. If you would try to set device language to a different one, localization should work. As for now, it is not possible to use in-app language on widget description and name localization.

like image 191
Jkrist Avatar answered Mar 11 '23 14:03

Jkrist


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"
         }
     }
    
like image 25
Bartłomiej Semańczyk Avatar answered Mar 11 '23 14:03

Bartłomiej Semańczyk