AppLanguage.swift 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // LoopFollow
  2. // AppLanguage.swift
  3. import Foundation
  4. /// User-selectable app interface language.
  5. ///
  6. /// `.system` follows the device language (the default). The other cases override
  7. /// it by writing the `AppleLanguages` user default, which iOS reads at launch to
  8. /// pick the bundle localization — so a change takes full effect after the app is
  9. /// restarted.
  10. enum AppLanguage: String, CaseIterable, Codable {
  11. case system
  12. case english
  13. case chineseSimplified
  14. var displayName: String {
  15. switch self {
  16. case .system: return String(localized: "System")
  17. case .english: return "English"
  18. case .chineseSimplified: return "简体中文"
  19. }
  20. }
  21. /// The `AppleLanguages` code this option maps to, or `nil` to follow the system.
  22. var languageCode: String? {
  23. switch self {
  24. case .system: return nil
  25. case .english: return "en"
  26. case .chineseSimplified: return "zh-Hans"
  27. }
  28. }
  29. /// Writes (or clears) the `AppleLanguages` preference so iOS localizes the app
  30. /// bundle accordingly on the next launch.
  31. func applyToAppleLanguages() {
  32. let defaults = UserDefaults.standard
  33. if let code = languageCode {
  34. defaults.set([code], forKey: "AppleLanguages")
  35. } else {
  36. defaults.removeObject(forKey: "AppleLanguages")
  37. }
  38. }
  39. /// Re-asserts the stored preference at launch to keep `AppleLanguages` in sync
  40. /// with the value shown in Settings.
  41. static func applyStored() {
  42. Storage.shared.appLanguage.value.applyToAppleLanguages()
  43. }
  44. }