FIRRemoteConfig.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. /*
  2. * Copyright 2019 Google
  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 <Foundation/Foundation.h>
  17. @class FIRApp;
  18. /// The Firebase Remote Config service default namespace, to be used if the API method does not
  19. /// specify a different namespace. Use the default namespace if configuring from the Google Firebase
  20. /// service.
  21. extern NSString *const _Nonnull FIRNamespaceGoogleMobilePlatform NS_SWIFT_NAME(
  22. NamespaceGoogleMobilePlatform);
  23. /// Key used to manage throttling in NSError user info when the refreshing of Remote Config
  24. /// parameter values (data) is throttled. The value of this key is the elapsed time since 1970,
  25. /// measured in seconds.
  26. extern NSString *const _Nonnull FIRRemoteConfigThrottledEndTimeInSecondsKey NS_SWIFT_NAME(
  27. RemoteConfigThrottledEndTimeInSecondsKey);
  28. /**
  29. * Listener registration returned by `addOnConfigUpdateListener`. Calling its method `remove` stops
  30. * the associated listener from receiving config updates and unregisters itself.
  31. *
  32. * If remove is called and no other listener registrations remain, the connection to the real-time
  33. * RC backend is closed. Subsequently calling `addOnConfigUpdateListener` will re-open the
  34. * connection.
  35. */
  36. NS_SWIFT_NAME(ConfigUpdateListenerRegistration)
  37. @interface FIRConfigUpdateListenerRegistration : NSObject
  38. /**
  39. * Removes the listener associated with this `ConfigUpdateListenerRegistration`. After the
  40. * initial call, subsequent calls have no effect.
  41. */
  42. - (void)remove;
  43. @end
  44. /// Indicates whether updated data was successfully fetched.
  45. typedef NS_ENUM(NSInteger, FIRRemoteConfigFetchStatus) {
  46. /// Config has never been fetched.
  47. FIRRemoteConfigFetchStatusNoFetchYet,
  48. /// Config fetch succeeded.
  49. FIRRemoteConfigFetchStatusSuccess,
  50. /// Config fetch failed.
  51. FIRRemoteConfigFetchStatusFailure,
  52. /// Config fetch was throttled.
  53. FIRRemoteConfigFetchStatusThrottled,
  54. } NS_SWIFT_NAME(RemoteConfigFetchStatus);
  55. /// Indicates whether updated data was successfully fetched and activated.
  56. typedef NS_ENUM(NSInteger, FIRRemoteConfigFetchAndActivateStatus) {
  57. /// The remote fetch succeeded and fetched data was activated.
  58. FIRRemoteConfigFetchAndActivateStatusSuccessFetchedFromRemote,
  59. /// The fetch and activate succeeded from already fetched but yet unexpired config data. You can
  60. /// control this using minimumFetchInterval property in FIRRemoteConfigSettings.
  61. FIRRemoteConfigFetchAndActivateStatusSuccessUsingPreFetchedData,
  62. /// The fetch and activate failed.
  63. FIRRemoteConfigFetchAndActivateStatusError
  64. } NS_SWIFT_NAME(RemoteConfigFetchAndActivateStatus);
  65. /// Remote Config error domain that handles errors when fetching data from the service.
  66. extern NSString *const _Nonnull FIRRemoteConfigErrorDomain NS_SWIFT_NAME(RemoteConfigErrorDomain);
  67. /// Firebase Remote Config service fetch error.
  68. typedef NS_ERROR_ENUM(FIRRemoteConfigErrorDomain, FIRRemoteConfigError){
  69. /// Unknown or no error.
  70. FIRRemoteConfigErrorUnknown = 8001,
  71. /// Frequency of fetch requests exceeds throttled limit.
  72. FIRRemoteConfigErrorThrottled = 8002,
  73. /// Internal error that covers all internal HTTP errors.
  74. FIRRemoteConfigErrorInternalError = 8003,
  75. } NS_SWIFT_NAME(RemoteConfigError);
  76. /// Remote Config error domain that handles errors for the real-time config update service.
  77. extern NSString *const _Nonnull FIRRemoteConfigUpdateErrorDomain NS_SWIFT_NAME(RemoteConfigUpdateErrorDomain);
  78. /// Firebase Remote Config real-time config update service error.
  79. typedef NS_ERROR_ENUM(FIRRemoteConfigUpdateErrorDomain, FIRRemoteConfigUpdateError){
  80. /// Unable to make a connection to the Remote Config backend.
  81. FIRRemoteConfigUpdateErrorStreamError = 8001,
  82. /// Unable to fetch the latest version of the config.
  83. FIRRemoteConfigUpdateErrorNotFetched = 8002,
  84. /// The ConfigUpdate message was unparsable.
  85. FIRRemoteConfigUpdateErrorMessageInvalid = 8003,
  86. /// The Remote Config real-time config update service is unavailable.
  87. FIRRemoteConfigUpdateErrorUnavailable = 8004,
  88. } NS_SWIFT_NAME(RemoteConfigUpdateError);
  89. /// Enumerated value that indicates the source of Remote Config data. Data can come from
  90. /// the Remote Config service, the DefaultConfig that is available when the app is first installed,
  91. /// or a static initialized value if data is not available from the service or DefaultConfig.
  92. typedef NS_ENUM(NSInteger, FIRRemoteConfigSource) {
  93. FIRRemoteConfigSourceRemote, ///< The data source is the Remote Config service.
  94. FIRRemoteConfigSourceDefault, ///< The data source is the DefaultConfig defined for this app.
  95. FIRRemoteConfigSourceStatic, ///< The data doesn't exist, return a static initialized value.
  96. } NS_SWIFT_NAME(RemoteConfigSource);
  97. /// Completion handler invoked by fetch methods when they get a response from the server.
  98. ///
  99. /// @param status Config fetching status.
  100. /// @param error Error message on failure.
  101. typedef void (^FIRRemoteConfigFetchCompletion)(FIRRemoteConfigFetchStatus status,
  102. NSError *_Nullable error)
  103. NS_SWIFT_UNAVAILABLE("Use Swift's closure syntax instead.");
  104. /// Completion handler invoked by activate method upon completion.
  105. /// @param error Error message on failure. Nil if activation was successful.
  106. typedef void (^FIRRemoteConfigActivateCompletion)(NSError *_Nullable error)
  107. NS_SWIFT_UNAVAILABLE("Use Swift's closure syntax instead.");
  108. /// Completion handler invoked upon completion of Remote Config initialization.
  109. ///
  110. /// @param initializationError nil if initialization succeeded.
  111. typedef void (^FIRRemoteConfigInitializationCompletion)(NSError *_Nullable initializationError)
  112. NS_SWIFT_UNAVAILABLE("Use Swift's closure syntax instead.");
  113. /// Completion handler invoked by the fetchAndActivate method. Used to convey status of fetch and,
  114. /// if successful, resultant activate call
  115. /// @param status Config fetching status.
  116. /// @param error Error message on failure of config fetch
  117. typedef void (^FIRRemoteConfigFetchAndActivateCompletion)(
  118. FIRRemoteConfigFetchAndActivateStatus status, NSError *_Nullable error)
  119. NS_SWIFT_UNAVAILABLE("Use Swift's closure syntax instead.");
  120. #pragma mark - FIRRemoteConfigValue
  121. /// This class provides a wrapper for Remote Config parameter values, with methods to get parameter
  122. /// values as different data types.
  123. NS_SWIFT_NAME(RemoteConfigValue)
  124. @interface FIRRemoteConfigValue : NSObject <NSCopying>
  125. /// Gets the value as a string.
  126. @property(nonatomic, readonly, nonnull) NSString *stringValue;
  127. /// Gets the value as a number value.
  128. @property(nonatomic, readonly, nonnull) NSNumber *numberValue;
  129. /// Gets the value as a NSData object.
  130. @property(nonatomic, readonly, nonnull) NSData *dataValue;
  131. /// Gets the value as a boolean.
  132. @property(nonatomic, readonly) BOOL boolValue;
  133. /// Gets a foundation object (NSDictionary / NSArray) by parsing the value as JSON. This method uses
  134. /// NSJSONSerialization's JSONObjectWithData method with an options value of 0.
  135. @property(nonatomic, readonly, nullable) id JSONValue NS_SWIFT_NAME(jsonValue);
  136. /// Identifies the source of the fetched value.
  137. @property(nonatomic, readonly) FIRRemoteConfigSource source;
  138. @end
  139. #pragma mark - FIRRemoteConfigSettings
  140. /// Firebase Remote Config settings.
  141. NS_SWIFT_NAME(RemoteConfigSettings)
  142. @interface FIRRemoteConfigSettings : NSObject
  143. /// Indicates the default value in seconds to set for the minimum interval that needs to elapse
  144. /// before a fetch request can again be made to the Remote Config backend. After a fetch request to
  145. /// the backend has succeeded, no additional fetch requests to the backend will be allowed until the
  146. /// minimum fetch interval expires. Note that you can override this default on a per-fetch request
  147. /// basis using `RemoteConfig.fetch(withExpirationDuration:)`. For example, setting
  148. /// the expiration duration to 0 in the fetch request will override the `minimumFetchInterval` and
  149. /// allow the request to proceed.
  150. @property(nonatomic, assign) NSTimeInterval minimumFetchInterval;
  151. /// Indicates the default value in seconds to abandon a pending fetch request made to the backend.
  152. /// This value is set for outgoing requests as the `timeoutIntervalForRequest` as well as the
  153. /// `timeoutIntervalForResource` on the `NSURLSession`'s configuration.
  154. @property(nonatomic, assign) NSTimeInterval fetchTimeout;
  155. @end
  156. #pragma mark - FIRRemoteConfigUpdate
  157. /// Used by Remote Config real-time config update service, this class represents changes between the
  158. /// newly fetched config and the current one. An instance of this class is passed to
  159. /// `FIRRemoteConfigUpdateCompletion` when a new config version has been automatically fetched.
  160. NS_SWIFT_NAME(RemoteConfigUpdate)
  161. @interface FIRRemoteConfigUpdate : NSObject
  162. /// Parameter keys whose values have been updated from the currently activated values. Includes
  163. /// keys that are added, deleted, and whose value, value source, or metadata has changed.
  164. @property(nonatomic, readonly, nonnull) NSSet<NSString *> *updatedKeys;
  165. @end
  166. #pragma mark - FIRRemoteConfig
  167. /// Firebase Remote Config class. The class method `remoteConfig()` can be used
  168. /// to fetch, activate and read config results and set default config results on the default
  169. /// Remote Config instance.
  170. NS_SWIFT_NAME(RemoteConfig)
  171. @interface FIRRemoteConfig : NSObject <NSFastEnumeration>
  172. /// Last successful fetch completion time.
  173. @property(nonatomic, readonly, strong, nullable) NSDate *lastFetchTime;
  174. /// Last fetch status. The status can be any enumerated value from `RemoteConfigFetchStatus`.
  175. @property(nonatomic, readonly, assign) FIRRemoteConfigFetchStatus lastFetchStatus;
  176. /// Config settings are custom settings.
  177. @property(nonatomic, readwrite, strong, nonnull) FIRRemoteConfigSettings *configSettings;
  178. /// Returns the `RemoteConfig` instance configured for the default Firebase app. This singleton
  179. /// object contains the complete set of Remote Config parameter values available to the app,
  180. /// including the Active Config and Default Config. This object also caches values fetched from the
  181. /// Remote Config server until they are copied to the Active Config by calling `activate()`. When
  182. /// you fetch values from the Remote Config server using the default Firebase app, you should use
  183. /// this class method to create and reuse a shared instance of `RemoteConfig`.
  184. + (nonnull FIRRemoteConfig *)remoteConfig NS_SWIFT_NAME(remoteConfig());
  185. /// Returns the `RemoteConfig` instance for your (non-default) Firebase appID. Note that Firebase
  186. /// analytics does not work for non-default app instances. This singleton object contains the
  187. /// complete set of Remote Config parameter values available to the app, including the Active Config
  188. /// and Default Config. This object also caches values fetched from the Remote Config Server until
  189. /// they are copied to the Active Config by calling `activate())`. When you fetch values
  190. /// from the Remote Config Server using the non-default Firebase app, you should use this
  191. /// class method to create and reuse shared instance of `RemoteConfig`.
  192. + (nonnull FIRRemoteConfig *)remoteConfigWithApp:(nonnull FIRApp *)app
  193. NS_SWIFT_NAME(remoteConfig(app:));
  194. /// Unavailable. Use +remoteConfig instead.
  195. - (nonnull instancetype)init __attribute__((unavailable("Use +remoteConfig instead.")));
  196. /// Ensures initialization is complete and clients can begin querying for Remote Config values.
  197. /// @param completionHandler Initialization complete callback with error parameter.
  198. - (void)ensureInitializedWithCompletionHandler:
  199. (void (^_Nonnull)(NSError *_Nullable initializationError))completionHandler;
  200. #pragma mark - Fetch
  201. /// Fetches Remote Config data with a callback. Call `activate()` to make fetched data
  202. /// available to your app.
  203. ///
  204. /// Note: This method uses a Firebase Installations token to identify the app instance, and once
  205. /// it's called, it periodically sends data to the Firebase backend. (see
  206. /// `Installations.authToken(completion:)`).
  207. /// To stop the periodic sync, call `Installations.delete(completion:)`
  208. /// and avoid calling this method again.
  209. ///
  210. /// @param completionHandler Fetch operation callback with status and error parameters.
  211. - (void)fetchWithCompletionHandler:(void (^_Nullable)(FIRRemoteConfigFetchStatus status,
  212. NSError *_Nullable error))completionHandler;
  213. /// Fetches Remote Config data and sets a duration that specifies how long config data lasts.
  214. /// Call `activateWithCompletion:` to make fetched data available to your app.
  215. ///
  216. /// Note: This method uses a Firebase Installations token to identify the app instance, and once
  217. /// it's called, it periodically sends data to the Firebase backend. (see
  218. /// `Installations.authToken(completion:)`).
  219. /// To stop the periodic sync, call `Installations.delete(completion:)`
  220. /// and avoid calling this method again.
  221. ///
  222. /// @param expirationDuration Override the (default or optionally set `minimumFetchInterval`
  223. /// property in RemoteConfigSettings) `minimumFetchInterval` for only the current request, in
  224. /// seconds. Setting a value of 0 seconds will force a fetch to the backend.
  225. /// @param completionHandler Fetch operation callback with status and error parameters.
  226. - (void)fetchWithExpirationDuration:(NSTimeInterval)expirationDuration
  227. completionHandler:(void (^_Nullable)(FIRRemoteConfigFetchStatus status,
  228. NSError *_Nullable error))completionHandler;
  229. /// Fetches Remote Config data and if successful, activates fetched data. Optional completion
  230. /// handler callback is invoked after the attempted activation of data, if the fetch call succeeded.
  231. ///
  232. /// Note: This method uses a Firebase Installations token to identify the app instance, and once
  233. /// it's called, it periodically sends data to the Firebase backend. (see
  234. /// `Installations.authToken(completion:)`).
  235. /// To stop the periodic sync, call `Installations.delete(completion:)`
  236. /// and avoid calling this method again.
  237. ///
  238. /// @param completionHandler Fetch operation callback with status and error parameters.
  239. - (void)fetchAndActivateWithCompletionHandler:
  240. (void (^_Nullable)(FIRRemoteConfigFetchAndActivateStatus status,
  241. NSError *_Nullable error))completionHandler;
  242. #pragma mark - Apply
  243. /// Applies Fetched Config data to the Active Config, causing updates to the behavior and appearance
  244. /// of the app to take effect (depending on how config data is used in the app).
  245. /// @param completion Activate operation callback with changed and error parameters.
  246. - (void)activateWithCompletion:(void (^_Nullable)(BOOL changed,
  247. NSError *_Nullable error))completion;
  248. #pragma mark - Get Config
  249. /// Enables access to configuration values by using object subscripting syntax.
  250. /// For example:
  251. /// let config = RemoteConfig.remoteConfig()
  252. /// let value = config["yourKey"]
  253. /// let boolValue = value.boolValue
  254. /// let number = config["yourKey"].numberValue
  255. - (nonnull FIRRemoteConfigValue *)objectForKeyedSubscript:(nonnull NSString *)key;
  256. /// Gets the config value.
  257. /// @param key Config key.
  258. - (nonnull FIRRemoteConfigValue *)configValueForKey:(nullable NSString *)key;
  259. /// Gets the config value of a given source from the default namespace.
  260. /// @param key Config key.
  261. /// @param source Config value source.
  262. - (nonnull FIRRemoteConfigValue *)configValueForKey:(nullable NSString *)key
  263. source:(FIRRemoteConfigSource)source;
  264. /// Gets all the parameter keys of a given source from the default namespace.
  265. ///
  266. /// @param source The config data source.
  267. /// @return An array of keys under the given source.
  268. - (nonnull NSArray<NSString *> *)allKeysFromSource:(FIRRemoteConfigSource)source;
  269. /// Returns the set of parameter keys that start with the given prefix, from the default namespace
  270. /// in the active config.
  271. ///
  272. /// @param prefix The key prefix to look for. If prefix is nil or empty, returns all the
  273. /// keys.
  274. /// @return The set of parameter keys that start with the specified prefix.
  275. - (nonnull NSSet<NSString *> *)keysWithPrefix:(nullable NSString *)prefix;
  276. #pragma mark - Defaults
  277. /// Sets config defaults for parameter keys and values in the default namespace config.
  278. /// @param defaults A dictionary mapping a NSString * key to a NSObject * value.
  279. - (void)setDefaults:(nullable NSDictionary<NSString *, NSObject *> *)defaults;
  280. /// Sets default configs from plist for default namespace.
  281. ///
  282. /// @param fileName The plist file name, with no file name extension. For example, if the plist file
  283. /// is named `defaultSamples.plist`:
  284. /// `RemoteConfig.remoteConfig().setDefaults(fromPlist: "defaultSamples")`
  285. - (void)setDefaultsFromPlistFileName:(nullable NSString *)fileName
  286. NS_SWIFT_NAME(setDefaults(fromPlist:));
  287. /// Returns the default value of a given key from the default config.
  288. ///
  289. /// @param key The parameter key of default config.
  290. /// @return Returns the default value of the specified key. Returns
  291. /// nil if the key doesn't exist in the default config.
  292. - (nullable FIRRemoteConfigValue *)defaultValueForKey:(nullable NSString *)key;
  293. #pragma mark - Real-time Config Updates
  294. /// Completion handler invoked by `addOnConfigUpdateListener` when there is an update to
  295. /// the config from the backend.
  296. ///
  297. /// @param configUpdate An instance of `FIRRemoteConfigUpdate` that contains information on which
  298. /// key's values have changed.
  299. /// @param error Error message on failure.
  300. typedef void (^FIRRemoteConfigUpdateCompletion)(FIRRemoteConfigUpdate *_Nullable configUpdate,
  301. NSError *_Nullable error)
  302. NS_SWIFT_UNAVAILABLE("Use Swift's closure syntax instead.");
  303. /// Start listening for real-time config updates from the Remote Config backend and automatically
  304. /// fetch updates when they're available.
  305. ///
  306. /// If a connection to the Remote Config backend is not already open, calling this method will
  307. /// open it. Multiple listeners can be added by calling this method again, but subsequent calls
  308. /// re-use the same connection to the backend.
  309. ///
  310. /// Note: Real-time Remote Config requires the Firebase Remote Config Realtime API. See Get started
  311. /// with Firebase Remote Config at https://firebase.google.com/docs/remote-config/get-started for
  312. /// more information.
  313. ///
  314. /// @param listener The configured listener that is called for every config update.
  315. /// @return Returns a registration representing the listener. The registration contains
  316. /// a remove method, which can be used to stop receiving updates for the provided listener.
  317. - (FIRConfigUpdateListenerRegistration *_Nonnull)addOnConfigUpdateListener:
  318. (FIRRemoteConfigUpdateCompletion _Nonnull)listener
  319. NS_SWIFT_NAME(addOnConfigUpdateListener(remoteConfigUpdateCompletion:));
  320. @end