RemoteConfigValueObservable.swift 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright 2022 Google LLC
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import FirebaseRemoteConfig
  17. import FirebaseCore
  18. import SwiftUI
  19. extension Notification.Name {
  20. // Listens to FirebaseRemoteConfig SDK if new configs are activated.
  21. static let onRemoteConfigActivated = Notification.Name("FIRRemoteConfigActivateNotification")
  22. }
  23. // Make sure this key is consistent with kFIRGoogleAppIDKey in FirebaseCore SDK
  24. let FirebaseRemoteConfigAppNameKey = "FIRAppNameKey"
  25. @available(iOS 14.0, macOS 11.0, macCatalyst 14.0, tvOS 14.0, watchOS 7.0, *)
  26. internal class RemoteConfigValueObservable<T: Decodable>: ObservableObject {
  27. @Published var configValue: T
  28. private let key: String
  29. private let remoteConfig: RemoteConfig
  30. private let fallbackValue: T
  31. init(key: String, fallbackValue: T) {
  32. self.key = key
  33. remoteConfig = RemoteConfig.remoteConfig()
  34. self.fallbackValue = fallbackValue
  35. // Initialize with fallback value
  36. configValue = fallbackValue
  37. // Check cached remote config value
  38. do {
  39. let configValue: RemoteConfigValue = remoteConfig[key]
  40. if configValue.source == .remote || configValue.source == .default {
  41. self.configValue = try remoteConfig[key].decoded()
  42. } else {
  43. self.configValue = fallbackValue
  44. }
  45. } catch {
  46. configValue = fallbackValue
  47. }
  48. NotificationCenter.default.addObserver(
  49. self, selector: #selector(configDidActivate), name: .onRemoteConfigActivated, object: nil
  50. )
  51. }
  52. @objc func configDidActivate(notification: NSNotification) {
  53. // This feature is only available in the default app.
  54. let appName = notification.userInfo?[FirebaseRemoteConfigAppNameKey] as? String
  55. if FirebaseApp.app()?.name != appName {
  56. return
  57. }
  58. do {
  59. let configValue: RemoteConfigValue = remoteConfig[key]
  60. if configValue.source == .remote {
  61. self.configValue = try remoteConfig[key].decoded()
  62. }
  63. } catch {
  64. // Suppresses a hard failure if decoding failed.
  65. }
  66. }
  67. }