FIRRemoteConfig.m 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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 "FirebaseRemoteConfig/Sources/Public/FirebaseRemoteConfig/FIRRemoteConfig.h"
  17. #import "FirebaseABTesting/Sources/Private/FirebaseABTestingInternal.h"
  18. #import "FirebaseCore/Extension/FirebaseCoreInternal.h"
  19. #import "FirebaseRemoteConfig/Sources/FIRRemoteConfigComponent.h"
  20. #import "FirebaseRemoteConfig/Sources/Private/FIRRemoteConfig_Private.h"
  21. #import "FirebaseRemoteConfig/Sources/Private/RCNConfigFetch.h"
  22. #import "FirebaseRemoteConfig/Sources/Private/RCNConfigSettings.h"
  23. #import "FirebaseRemoteConfig/Sources/RCNConfigConstants.h"
  24. #import "FirebaseRemoteConfig/Sources/RCNConfigContent.h"
  25. #import "FirebaseRemoteConfig/Sources/RCNConfigDBManager.h"
  26. #import "FirebaseRemoteConfig/Sources/RCNConfigExperiment.h"
  27. #import "FirebaseRemoteConfig/Sources/RCNConfigValue_Internal.h"
  28. #import "FirebaseRemoteConfig/Sources/RCNDevice.h"
  29. #import "FirebaseRemoteConfig/Sources/RCNPersonalization.h"
  30. /// Remote Config Error Domain.
  31. /// TODO: Rename according to obj-c style for constants.
  32. NSString *const FIRRemoteConfigErrorDomain = @"com.google.remoteconfig.ErrorDomain";
  33. /// Remote Config Error Info End Time Seconds;
  34. NSString *const FIRRemoteConfigThrottledEndTimeInSecondsKey = @"error_throttled_end_time_seconds";
  35. /// Minimum required time interval between fetch requests made to the backend.
  36. static NSString *const kRemoteConfigMinimumFetchIntervalKey = @"_rcn_minimum_fetch_interval";
  37. /// Timeout value for waiting on a fetch response.
  38. static NSString *const kRemoteConfigFetchTimeoutKey = @"_rcn_fetch_timeout";
  39. /// Notification when config is successfully activated
  40. const NSNotificationName FIRRemoteConfigActivateNotification =
  41. @"FIRRemoteConfigActivateNotification";
  42. /// Listener for the get methods.
  43. typedef void (^FIRRemoteConfigListener)(NSString *_Nonnull, NSDictionary *_Nonnull);
  44. @implementation FIRRemoteConfigSettings
  45. - (instancetype)init {
  46. self = [super init];
  47. if (self) {
  48. _minimumFetchInterval = RCNDefaultMinimumFetchInterval;
  49. _fetchTimeout = RCNHTTPDefaultConnectionTimeout;
  50. }
  51. return self;
  52. }
  53. @end
  54. @implementation FIRRemoteConfig {
  55. /// All the config content.
  56. RCNConfigContent *_configContent;
  57. RCNConfigDBManager *_DBManager;
  58. RCNConfigSettings *_settings;
  59. RCNConfigFetch *_configFetch;
  60. RCNConfigExperiment *_configExperiment;
  61. dispatch_queue_t _queue;
  62. NSString *_appName;
  63. NSMutableArray *_listeners;
  64. }
  65. static NSMutableDictionary<NSString *, NSMutableDictionary<NSString *, FIRRemoteConfig *> *>
  66. *RCInstances;
  67. + (nonnull FIRRemoteConfig *)remoteConfigWithApp:(FIRApp *_Nonnull)firebaseApp {
  68. return [FIRRemoteConfig remoteConfigWithFIRNamespace:FIRNamespaceGoogleMobilePlatform
  69. app:firebaseApp];
  70. }
  71. + (nonnull FIRRemoteConfig *)remoteConfigWithFIRNamespace:(NSString *_Nonnull)firebaseNamespace {
  72. if (![FIRApp isDefaultAppConfigured]) {
  73. [NSException raise:@"FIRAppNotConfigured"
  74. format:@"The default `FirebaseApp` instance must be configured before the "
  75. @"default Remote Config instance can be initialized. One way to ensure this "
  76. @"is to call `FirebaseApp.configure()` in the App Delegate's "
  77. @"`application(_:didFinishLaunchingWithOptions:)` or the `@main` struct's "
  78. @"initializer in SwiftUI."];
  79. }
  80. return [FIRRemoteConfig remoteConfigWithFIRNamespace:firebaseNamespace app:[FIRApp defaultApp]];
  81. }
  82. + (nonnull FIRRemoteConfig *)remoteConfigWithFIRNamespace:(NSString *_Nonnull)firebaseNamespace
  83. app:(FIRApp *_Nonnull)firebaseApp {
  84. // Use the provider to generate and return instances of FIRRemoteConfig for this specific app and
  85. // namespace. This will ensure the app is configured before Remote Config can return an instance.
  86. id<FIRRemoteConfigProvider> provider =
  87. FIR_COMPONENT(FIRRemoteConfigProvider, firebaseApp.container);
  88. return [provider remoteConfigForNamespace:firebaseNamespace];
  89. }
  90. + (FIRRemoteConfig *)remoteConfig {
  91. // If the default app is not configured at this point, warn the developer.
  92. if (![FIRApp isDefaultAppConfigured]) {
  93. [NSException raise:@"FIRAppNotConfigured"
  94. format:@"The default `FirebaseApp` instance must be configured before the "
  95. @"default Remote Config instance can be initialized. One way to ensure this "
  96. @"is to call `FirebaseApp.configure()` in the App Delegate's "
  97. @"`application(_:didFinishLaunchingWithOptions:)` or the `@main` struct's "
  98. @"initializer in SwiftUI."];
  99. }
  100. return [FIRRemoteConfig remoteConfigWithFIRNamespace:FIRNamespaceGoogleMobilePlatform
  101. app:[FIRApp defaultApp]];
  102. }
  103. /// Singleton instance of serial queue for queuing all incoming RC calls.
  104. + (dispatch_queue_t)sharedRemoteConfigSerialQueue {
  105. static dispatch_once_t onceToken;
  106. static dispatch_queue_t sharedRemoteConfigQueue;
  107. dispatch_once(&onceToken, ^{
  108. sharedRemoteConfigQueue =
  109. dispatch_queue_create(RCNRemoteConfigQueueLabel, DISPATCH_QUEUE_SERIAL);
  110. });
  111. return sharedRemoteConfigQueue;
  112. }
  113. /// Designated initializer
  114. - (instancetype)initWithAppName:(NSString *)appName
  115. FIROptions:(FIROptions *)options
  116. namespace:(NSString *)FIRNamespace
  117. DBManager:(RCNConfigDBManager *)DBManager
  118. configContent:(RCNConfigContent *)configContent
  119. analytics:(nullable id<FIRAnalyticsInterop>)analytics {
  120. self = [super init];
  121. if (self) {
  122. _appName = appName;
  123. _DBManager = DBManager;
  124. // The fully qualified Firebase namespace is namespace:firappname.
  125. _FIRNamespace = [NSString stringWithFormat:@"%@:%@", FIRNamespace, appName];
  126. // Initialize RCConfigContent if not already.
  127. _configContent = configContent;
  128. _settings = [[RCNConfigSettings alloc] initWithDatabaseManager:_DBManager
  129. namespace:_FIRNamespace
  130. firebaseAppName:appName
  131. googleAppID:options.googleAppID];
  132. FIRExperimentController *experimentController = [FIRExperimentController sharedInstance];
  133. _configExperiment = [[RCNConfigExperiment alloc] initWithDBManager:_DBManager
  134. experimentController:experimentController];
  135. /// Serial queue for read and write lock.
  136. _queue = [FIRRemoteConfig sharedRemoteConfigSerialQueue];
  137. // Initialize with default config settings.
  138. [self setDefaultConfigSettings];
  139. _configFetch = [[RCNConfigFetch alloc] initWithContent:_configContent
  140. DBManager:_DBManager
  141. settings:_settings
  142. analytics:analytics
  143. experiment:_configExperiment
  144. queue:_queue
  145. namespace:_FIRNamespace
  146. options:options];
  147. [_settings loadConfigFromMetadataTable];
  148. if (analytics) {
  149. _listeners = [[NSMutableArray alloc] init];
  150. RCNPersonalization *personalization =
  151. [[RCNPersonalization alloc] initWithAnalytics:analytics];
  152. [self addListener:^(NSString *key, NSDictionary *config) {
  153. [personalization logArmActive:key config:config];
  154. }];
  155. }
  156. }
  157. return self;
  158. }
  159. // Initialize with default config settings.
  160. - (void)setDefaultConfigSettings {
  161. // Set the default config settings.
  162. self->_settings.fetchTimeout = RCNHTTPDefaultConnectionTimeout;
  163. self->_settings.minimumFetchInterval = RCNDefaultMinimumFetchInterval;
  164. }
  165. - (void)ensureInitializedWithCompletionHandler:
  166. (nonnull FIRRemoteConfigInitializationCompletion)completionHandler {
  167. __weak FIRRemoteConfig *weakSelf = self;
  168. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  169. FIRRemoteConfig *strongSelf = weakSelf;
  170. if (!strongSelf) {
  171. return;
  172. }
  173. BOOL initializationSuccess = [self->_configContent initializationSuccessful];
  174. NSError *error = nil;
  175. if (!initializationSuccess) {
  176. error = [[NSError alloc]
  177. initWithDomain:FIRRemoteConfigErrorDomain
  178. code:FIRRemoteConfigErrorInternalError
  179. userInfo:@{NSLocalizedDescriptionKey : @"Timed out waiting for database load."}];
  180. }
  181. completionHandler(error);
  182. });
  183. }
  184. /// Adds a listener that will be called whenever one of the get methods is called.
  185. /// @param listener Function that takes in the parameter key and the config.
  186. - (void)addListener:(nonnull FIRRemoteConfigListener)listener {
  187. @synchronized(_listeners) {
  188. [_listeners addObject:listener];
  189. }
  190. }
  191. - (void)callListeners:(NSString *)key config:(NSDictionary *)config {
  192. @synchronized(_listeners) {
  193. for (FIRRemoteConfigListener listener in _listeners) {
  194. dispatch_async(_queue, ^{
  195. listener(key, config);
  196. });
  197. }
  198. }
  199. }
  200. #pragma mark - fetch
  201. - (void)fetchWithCompletionHandler:(FIRRemoteConfigFetchCompletion)completionHandler {
  202. dispatch_async(_queue, ^{
  203. [self fetchWithExpirationDuration:self->_settings.minimumFetchInterval
  204. completionHandler:completionHandler];
  205. });
  206. }
  207. - (void)fetchWithExpirationDuration:(NSTimeInterval)expirationDuration
  208. completionHandler:(FIRRemoteConfigFetchCompletion)completionHandler {
  209. FIRRemoteConfigFetchCompletion completionHandlerCopy = nil;
  210. if (completionHandler) {
  211. completionHandlerCopy = [completionHandler copy];
  212. }
  213. [_configFetch fetchConfigWithExpirationDuration:expirationDuration
  214. completionHandler:completionHandlerCopy];
  215. }
  216. #pragma mark - fetchAndActivate
  217. - (void)fetchAndActivateWithCompletionHandler:
  218. (FIRRemoteConfigFetchAndActivateCompletion)completionHandler {
  219. __weak FIRRemoteConfig *weakSelf = self;
  220. FIRRemoteConfigFetchCompletion fetchCompletion =
  221. ^(FIRRemoteConfigFetchStatus fetchStatus, NSError *fetchError) {
  222. FIRRemoteConfig *strongSelf = weakSelf;
  223. if (!strongSelf) {
  224. return;
  225. }
  226. // Fetch completed. We are being called on the main queue.
  227. // If fetch is successful, try to activate the fetched config
  228. if (fetchStatus == FIRRemoteConfigFetchStatusSuccess && !fetchError) {
  229. [strongSelf activateWithCompletion:^(BOOL changed, NSError *_Nullable activateError) {
  230. if (completionHandler) {
  231. FIRRemoteConfigFetchAndActivateStatus status =
  232. activateError ? FIRRemoteConfigFetchAndActivateStatusSuccessUsingPreFetchedData
  233. : FIRRemoteConfigFetchAndActivateStatusSuccessFetchedFromRemote;
  234. dispatch_async(dispatch_get_main_queue(), ^{
  235. completionHandler(status, nil);
  236. });
  237. }
  238. }];
  239. } else if (completionHandler) {
  240. FIRRemoteConfigFetchAndActivateStatus status =
  241. fetchStatus == FIRRemoteConfigFetchStatusSuccess
  242. ? FIRRemoteConfigFetchAndActivateStatusSuccessUsingPreFetchedData
  243. : FIRRemoteConfigFetchAndActivateStatusError;
  244. dispatch_async(dispatch_get_main_queue(), ^{
  245. completionHandler(status, fetchError);
  246. });
  247. }
  248. };
  249. [self fetchWithCompletionHandler:fetchCompletion];
  250. }
  251. #pragma mark - activate
  252. typedef void (^FIRRemoteConfigActivateChangeCompletion)(BOOL changed, NSError *_Nullable error);
  253. - (void)activateWithCompletion:(FIRRemoteConfigActivateChangeCompletion)completion {
  254. __weak FIRRemoteConfig *weakSelf = self;
  255. void (^applyBlock)(void) = ^(void) {
  256. FIRRemoteConfig *strongSelf = weakSelf;
  257. if (!strongSelf) {
  258. NSError *error = [NSError errorWithDomain:FIRRemoteConfigErrorDomain
  259. code:FIRRemoteConfigErrorInternalError
  260. userInfo:@{@"ActivationFailureReason" : @"Internal Error."}];
  261. if (completion) {
  262. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  263. completion(NO, error);
  264. });
  265. }
  266. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000068", @"Internal error activating config.");
  267. return;
  268. }
  269. // Check if the last fetched config has already been activated. Fetches with no data change are
  270. // ignored.
  271. if (strongSelf->_settings.lastETagUpdateTime == 0 ||
  272. strongSelf->_settings.lastETagUpdateTime <= strongSelf->_settings.lastApplyTimeInterval) {
  273. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000069",
  274. @"Most recently fetched config is already activated.");
  275. if (completion) {
  276. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  277. completion(NO, nil);
  278. });
  279. }
  280. return;
  281. }
  282. [strongSelf->_configContent copyFromDictionary:self->_configContent.fetchedConfig
  283. toSource:RCNDBSourceActive
  284. forNamespace:self->_FIRNamespace];
  285. strongSelf->_settings.lastApplyTimeInterval = [[NSDate date] timeIntervalSince1970];
  286. // New config has been activated at this point
  287. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000069", @"Config activated.");
  288. [strongSelf->_configContent activatePersonalization];
  289. // Update experiments only for 3p namespace
  290. NSString *namespace = [strongSelf->_FIRNamespace
  291. substringToIndex:[strongSelf->_FIRNamespace rangeOfString:@":"].location];
  292. if ([namespace isEqualToString:FIRNamespaceGoogleMobilePlatform]) {
  293. dispatch_async(dispatch_get_main_queue(), ^{
  294. [self notifyConfigHasActivated];
  295. });
  296. [strongSelf->_configExperiment updateExperimentsWithHandler:^(NSError *_Nullable error) {
  297. if (completion) {
  298. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  299. completion(YES, nil);
  300. });
  301. }
  302. }];
  303. } else {
  304. if (completion) {
  305. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  306. completion(YES, nil);
  307. });
  308. }
  309. }
  310. };
  311. dispatch_async(_queue, applyBlock);
  312. }
  313. - (void)notifyConfigHasActivated {
  314. // Need a valid google app name.
  315. if (!_appName) {
  316. return;
  317. }
  318. // The Remote Config Swift SDK will be listening for this notification so it can tell SwiftUI to
  319. // update the UI.
  320. NSDictionary *appInfoDict = @{kFIRAppNameKey : _appName};
  321. [[NSNotificationCenter defaultCenter] postNotificationName:FIRRemoteConfigActivateNotification
  322. object:self
  323. userInfo:appInfoDict];
  324. }
  325. #pragma mark - helpers
  326. - (NSString *)fullyQualifiedNamespace:(NSString *)namespace {
  327. // If this is already a fully qualified namespace, return.
  328. if ([namespace rangeOfString:@":"].location != NSNotFound) {
  329. return namespace;
  330. }
  331. NSString *fullyQualifiedNamespace = [NSString stringWithFormat:@"%@:%@", namespace, _appName];
  332. return fullyQualifiedNamespace;
  333. }
  334. #pragma mark - Get Config Result
  335. - (FIRRemoteConfigValue *)objectForKeyedSubscript:(NSString *)key {
  336. return [self configValueForKey:key];
  337. }
  338. - (FIRRemoteConfigValue *)configValueForKey:(NSString *)key {
  339. if (!key) {
  340. return [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  341. source:FIRRemoteConfigSourceStatic];
  342. }
  343. NSString *FQNamespace = [self fullyQualifiedNamespace:_FIRNamespace];
  344. __block FIRRemoteConfigValue *value;
  345. dispatch_sync(_queue, ^{
  346. value = self->_configContent.activeConfig[FQNamespace][key];
  347. if (value) {
  348. if (value.source != FIRRemoteConfigSourceRemote) {
  349. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000001",
  350. @"Key %@ should come from source:%zd instead coming from source: %zd.", key,
  351. (long)FIRRemoteConfigSourceRemote, (long)value.source);
  352. }
  353. [self callListeners:key
  354. config:[self->_configContent getConfigAndMetadataForNamespace:FQNamespace]];
  355. return;
  356. }
  357. value = self->_configContent.defaultConfig[FQNamespace][key];
  358. if (value) {
  359. return;
  360. }
  361. value = [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  362. source:FIRRemoteConfigSourceStatic];
  363. });
  364. return value;
  365. }
  366. - (FIRRemoteConfigValue *)configValueForKey:(NSString *)key source:(FIRRemoteConfigSource)source {
  367. if (!key) {
  368. return [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  369. source:FIRRemoteConfigSourceStatic];
  370. }
  371. NSString *FQNamespace = [self fullyQualifiedNamespace:_FIRNamespace];
  372. __block FIRRemoteConfigValue *value;
  373. dispatch_sync(_queue, ^{
  374. if (source == FIRRemoteConfigSourceRemote) {
  375. value = self->_configContent.activeConfig[FQNamespace][key];
  376. } else if (source == FIRRemoteConfigSourceDefault) {
  377. value = self->_configContent.defaultConfig[FQNamespace][key];
  378. } else {
  379. value = [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  380. source:FIRRemoteConfigSourceStatic];
  381. }
  382. });
  383. return value;
  384. }
  385. - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state
  386. objects:(id __unsafe_unretained[])stackbuf
  387. count:(NSUInteger)len {
  388. __block NSUInteger localValue;
  389. dispatch_sync(_queue, ^{
  390. localValue =
  391. [self->_configContent.activeConfig[self->_FIRNamespace] countByEnumeratingWithState:state
  392. objects:stackbuf
  393. count:len];
  394. });
  395. return localValue;
  396. }
  397. #pragma mark - Properties
  398. /// Last fetch completion time.
  399. - (NSDate *)lastFetchTime {
  400. __block NSDate *fetchTime;
  401. dispatch_sync(_queue, ^{
  402. NSTimeInterval lastFetchTime = self->_settings.lastFetchTimeInterval;
  403. fetchTime = [NSDate dateWithTimeIntervalSince1970:lastFetchTime];
  404. });
  405. return fetchTime;
  406. }
  407. - (FIRRemoteConfigFetchStatus)lastFetchStatus {
  408. __block FIRRemoteConfigFetchStatus currentStatus;
  409. dispatch_sync(_queue, ^{
  410. currentStatus = self->_settings.lastFetchStatus;
  411. });
  412. return currentStatus;
  413. }
  414. - (NSArray *)allKeysFromSource:(FIRRemoteConfigSource)source {
  415. __block NSArray *keys = [[NSArray alloc] init];
  416. dispatch_sync(_queue, ^{
  417. NSString *FQNamespace = [self fullyQualifiedNamespace:self->_FIRNamespace];
  418. switch (source) {
  419. case FIRRemoteConfigSourceDefault:
  420. if (self->_configContent.defaultConfig[FQNamespace]) {
  421. keys = [[self->_configContent.defaultConfig[FQNamespace] allKeys] copy];
  422. }
  423. break;
  424. case FIRRemoteConfigSourceRemote:
  425. if (self->_configContent.activeConfig[FQNamespace]) {
  426. keys = [[self->_configContent.activeConfig[FQNamespace] allKeys] copy];
  427. }
  428. break;
  429. default:
  430. break;
  431. }
  432. });
  433. return keys;
  434. }
  435. - (nonnull NSSet *)keysWithPrefix:(nullable NSString *)prefix {
  436. __block NSMutableSet *keys = [[NSMutableSet alloc] init];
  437. dispatch_sync(_queue, ^{
  438. NSString *FQNamespace = [self fullyQualifiedNamespace:self->_FIRNamespace];
  439. if (self->_configContent.activeConfig[FQNamespace]) {
  440. NSArray *allKeys = [self->_configContent.activeConfig[FQNamespace] allKeys];
  441. if (!prefix.length) {
  442. keys = [NSMutableSet setWithArray:allKeys];
  443. } else {
  444. for (NSString *key in allKeys) {
  445. if ([key hasPrefix:prefix]) {
  446. [keys addObject:key];
  447. }
  448. }
  449. }
  450. }
  451. });
  452. return [keys copy];
  453. }
  454. #pragma mark - Defaults
  455. - (void)setDefaults:(NSDictionary<NSString *, NSObject *> *)defaultConfig {
  456. NSString *FQNamespace = [self fullyQualifiedNamespace:_FIRNamespace];
  457. NSDictionary *defaultConfigCopy = [[NSDictionary alloc] init];
  458. if (defaultConfig) {
  459. defaultConfigCopy = [defaultConfig copy];
  460. }
  461. void (^setDefaultsBlock)(void) = ^(void) {
  462. NSDictionary *namespaceToDefaults = @{FQNamespace : defaultConfigCopy};
  463. [self->_configContent copyFromDictionary:namespaceToDefaults
  464. toSource:RCNDBSourceDefault
  465. forNamespace:FQNamespace];
  466. self->_settings.lastSetDefaultsTimeInterval = [[NSDate date] timeIntervalSince1970];
  467. };
  468. dispatch_async(_queue, setDefaultsBlock);
  469. }
  470. - (FIRRemoteConfigValue *)defaultValueForKey:(NSString *)key {
  471. NSString *FQNamespace = [self fullyQualifiedNamespace:_FIRNamespace];
  472. __block FIRRemoteConfigValue *value;
  473. dispatch_sync(_queue, ^{
  474. NSDictionary *defaultConfig = self->_configContent.defaultConfig;
  475. value = defaultConfig[FQNamespace][key];
  476. if (value) {
  477. if (value.source != FIRRemoteConfigSourceDefault) {
  478. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000002",
  479. @"Key %@ should come from source:%zd instead coming from source: %zd", key,
  480. (long)FIRRemoteConfigSourceDefault, (long)value.source);
  481. }
  482. }
  483. });
  484. return value;
  485. }
  486. - (void)setDefaultsFromPlistFileName:(nullable NSString *)fileName {
  487. if (!fileName || fileName.length == 0) {
  488. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000037",
  489. @"The plist file '%@' could not be found by Remote Config.", fileName);
  490. return;
  491. }
  492. NSArray *bundles = @[ [NSBundle mainBundle], [NSBundle bundleForClass:[self class]] ];
  493. for (NSBundle *bundle in bundles) {
  494. NSString *plistFile = [bundle pathForResource:fileName ofType:@"plist"];
  495. // Use the first one we find.
  496. if (plistFile) {
  497. NSDictionary *defaultConfig = [[NSDictionary alloc] initWithContentsOfFile:plistFile];
  498. if (defaultConfig) {
  499. [self setDefaults:defaultConfig];
  500. }
  501. return;
  502. }
  503. }
  504. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000037",
  505. @"The plist file '%@' could not be found by Remote Config.", fileName);
  506. }
  507. #pragma mark - custom variables
  508. - (FIRRemoteConfigSettings *)configSettings {
  509. __block NSTimeInterval minimumFetchInterval = RCNDefaultMinimumFetchInterval;
  510. __block NSTimeInterval fetchTimeout = RCNHTTPDefaultConnectionTimeout;
  511. dispatch_sync(_queue, ^{
  512. minimumFetchInterval = self->_settings.minimumFetchInterval;
  513. fetchTimeout = self->_settings.fetchTimeout;
  514. });
  515. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000066",
  516. @"Successfully read configSettings. Minimum Fetch Interval:%f, "
  517. @"Fetch timeout: %f",
  518. minimumFetchInterval, fetchTimeout);
  519. FIRRemoteConfigSettings *settings = [[FIRRemoteConfigSettings alloc] init];
  520. settings.minimumFetchInterval = minimumFetchInterval;
  521. settings.fetchTimeout = fetchTimeout;
  522. /// The NSURLSession needs to be recreated whenever the fetch timeout may be updated.
  523. [_configFetch recreateNetworkSession];
  524. return settings;
  525. }
  526. - (void)setConfigSettings:(FIRRemoteConfigSettings *)configSettings {
  527. void (^setConfigSettingsBlock)(void) = ^(void) {
  528. if (!configSettings) {
  529. return;
  530. }
  531. self->_settings.minimumFetchInterval = configSettings.minimumFetchInterval;
  532. self->_settings.fetchTimeout = configSettings.fetchTimeout;
  533. /// The NSURLSession needs to be recreated whenever the fetch timeout may be updated.
  534. [self->_configFetch recreateNetworkSession];
  535. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000067",
  536. @"Successfully set configSettings. Minimum Fetch Interval:%f, "
  537. @"Fetch timeout:%f",
  538. configSettings.minimumFetchInterval, configSettings.fetchTimeout);
  539. };
  540. dispatch_async(_queue, setConfigSettingsBlock);
  541. }
  542. @end