RemoteConfigValueObservable.swift 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. #if SWIFT_PACKAGE
  17. @_exported import FirebaseRemoteConfigInternal
  18. #endif // SWIFT_PACKAGE
  19. import FirebaseCore
  20. import SwiftUI
  21. extension Notification.Name {
  22. // Listens to FirebaseRemoteConfig SDK if new configs are activated.
  23. static let onRemoteConfigActivated = Notification.Name("FIRRemoteConfigActivateNotification")
  24. }
  25. // Make sure this key is consistent with kFIRGoogleAppIDKey in FirebaseCore SDK
  26. let FirebaseRemoteConfigAppNameKey = "FIRAppNameKey"
  27. @available(iOS 14.0, macOS 11.0, macCatalyst 14.0, tvOS 14.0, watchOS 7.0, *)
  28. class RemoteConfigValueObservable<T: Decodable>: ObservableObject {
  29. @Published var configValue: T
  30. private let key: String
  31. private let remoteConfig: RemoteConfig
  32. private let fallbackValue: T
  33. init(key: String, fallbackValue: T) {
  34. self.key = key
  35. remoteConfig = RemoteConfig.remoteConfig()
  36. self.fallbackValue = fallbackValue
  37. // Initialize with fallback value
  38. configValue = fallbackValue
  39. // Check cached remote config value
  40. do {
  41. let configValue: RemoteConfigValue = remoteConfig[key]
  42. if configValue.source == .remote || configValue.source == .default {
  43. self.configValue = try remoteConfig[key].decoded()
  44. } else {
  45. self.configValue = fallbackValue
  46. }
  47. } catch {
  48. configValue = fallbackValue
  49. }
  50. NotificationCenter.default.addObserver(
  51. self, selector: #selector(configDidActivate), name: .onRemoteConfigActivated, object: nil
  52. )
  53. }
  54. @objc func configDidActivate(notification: NSNotification) {
  55. // This feature is only available in the default app.
  56. let appName = notification.userInfo?[FirebaseRemoteConfigAppNameKey] as? String
  57. if FirebaseApp.app()?.name != appName {
  58. return
  59. }
  60. do {
  61. let configValue: RemoteConfigValue = remoteConfig[key]
  62. if configValue.source == .remote {
  63. self.configValue = try remoteConfig[key].decoded()
  64. }
  65. } catch {
  66. // Suppresses a hard failure if decoding failed.
  67. }
  68. }
  69. }