RemoteConfigValueObservable.swift 2.3 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. applyConfigValue()
  39. NotificationCenter.default.addObserver(
  40. self, selector: #selector(configDidActivate), name: .onRemoteConfigActivated, object: nil
  41. )
  42. }
  43. @objc func configDidActivate(notification: NSNotification) {
  44. // This feature is only available in the default app.
  45. let appName = notification.userInfo?[FirebaseRemoteConfigAppNameKey] as? String
  46. if FirebaseApp.app()?.name != appName {
  47. return
  48. }
  49. applyConfigValue()
  50. }
  51. private func applyConfigValue() {
  52. do {
  53. let configValue: RemoteConfigValue = remoteConfig[key]
  54. if configValue.source == .remote || configValue.source == .default {
  55. self.configValue = try remoteConfig[key].decoded()
  56. } else {
  57. self.configValue = fallbackValue
  58. }
  59. } catch {
  60. configValue = fallbackValue
  61. }
  62. }
  63. }