FIRRemoteConfig.m 23 KB

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