FIRRemoteConfig.m 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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. [strongSelf->_configExperiment updateExperimentsWithHandler:^(NSError *_Nullable error) {
  286. if (completion) {
  287. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  288. completion(YES, nil);
  289. });
  290. }
  291. }];
  292. };
  293. dispatch_async(_queue, applyBlock);
  294. }
  295. #pragma mark - helpers
  296. - (NSString *)fullyQualifiedNamespace:(NSString *)namespace {
  297. // If this is already a fully qualified namespace, return.
  298. if ([namespace rangeOfString:@":"].location != NSNotFound) {
  299. return namespace;
  300. }
  301. NSString *fullyQualifiedNamespace = [NSString stringWithFormat:@"%@:%@", namespace, _appName];
  302. return fullyQualifiedNamespace;
  303. }
  304. #pragma mark - Get Config Result
  305. - (FIRRemoteConfigValue *)objectForKeyedSubscript:(NSString *)key {
  306. return [self configValueForKey:key];
  307. }
  308. - (FIRRemoteConfigValue *)configValueForKey:(NSString *)key {
  309. if (!key) {
  310. return [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  311. source:FIRRemoteConfigSourceStatic];
  312. }
  313. NSString *FQNamespace = [self fullyQualifiedNamespace:_FIRNamespace];
  314. __block FIRRemoteConfigValue *value;
  315. dispatch_sync(_queue, ^{
  316. value = self->_configContent.activeConfig[FQNamespace][key];
  317. if (value) {
  318. if (value.source != FIRRemoteConfigSourceRemote) {
  319. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000001",
  320. @"Key %@ should come from source:%zd instead coming from source: %zd.", key,
  321. (long)FIRRemoteConfigSourceRemote, (long)value.source);
  322. }
  323. [self callListeners:key
  324. config:[self->_configContent getConfigAndMetadataForNamespace:FQNamespace]];
  325. return;
  326. }
  327. value = self->_configContent.defaultConfig[FQNamespace][key];
  328. if (value) {
  329. return;
  330. }
  331. value = [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  332. source:FIRRemoteConfigSourceStatic];
  333. });
  334. return value;
  335. }
  336. - (FIRRemoteConfigValue *)configValueForKey:(NSString *)key source:(FIRRemoteConfigSource)source {
  337. if (!key) {
  338. return [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  339. source:FIRRemoteConfigSourceStatic];
  340. }
  341. NSString *FQNamespace = [self fullyQualifiedNamespace:_FIRNamespace];
  342. __block FIRRemoteConfigValue *value;
  343. dispatch_sync(_queue, ^{
  344. if (source == FIRRemoteConfigSourceRemote) {
  345. value = self->_configContent.activeConfig[FQNamespace][key];
  346. } else if (source == FIRRemoteConfigSourceDefault) {
  347. value = self->_configContent.defaultConfig[FQNamespace][key];
  348. } else {
  349. value = [[FIRRemoteConfigValue alloc] initWithData:[NSData data]
  350. source:FIRRemoteConfigSourceStatic];
  351. }
  352. });
  353. return value;
  354. }
  355. - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state
  356. objects:(id __unsafe_unretained[])stackbuf
  357. count:(NSUInteger)len {
  358. __block NSUInteger localValue;
  359. dispatch_sync(_queue, ^{
  360. localValue =
  361. [self->_configContent.activeConfig[self->_FIRNamespace] countByEnumeratingWithState:state
  362. objects:stackbuf
  363. count:len];
  364. });
  365. return localValue;
  366. }
  367. #pragma mark - Properties
  368. /// Last fetch completion time.
  369. - (NSDate *)lastFetchTime {
  370. __block NSDate *fetchTime;
  371. dispatch_sync(_queue, ^{
  372. NSTimeInterval lastFetchTime = self->_settings.lastFetchTimeInterval;
  373. fetchTime = [NSDate dateWithTimeIntervalSince1970:lastFetchTime];
  374. });
  375. return fetchTime;
  376. }
  377. - (FIRRemoteConfigFetchStatus)lastFetchStatus {
  378. __block FIRRemoteConfigFetchStatus currentStatus;
  379. dispatch_sync(_queue, ^{
  380. currentStatus = self->_settings.lastFetchStatus;
  381. });
  382. return currentStatus;
  383. }
  384. - (NSArray *)allKeysFromSource:(FIRRemoteConfigSource)source {
  385. __block NSArray *keys = [[NSArray alloc] init];
  386. dispatch_sync(_queue, ^{
  387. NSString *FQNamespace = [self fullyQualifiedNamespace:self->_FIRNamespace];
  388. switch (source) {
  389. case FIRRemoteConfigSourceDefault:
  390. if (self->_configContent.defaultConfig[FQNamespace]) {
  391. keys = [[self->_configContent.defaultConfig[FQNamespace] allKeys] copy];
  392. }
  393. break;
  394. case FIRRemoteConfigSourceRemote:
  395. if (self->_configContent.activeConfig[FQNamespace]) {
  396. keys = [[self->_configContent.activeConfig[FQNamespace] allKeys] copy];
  397. }
  398. break;
  399. default:
  400. break;
  401. }
  402. });
  403. return keys;
  404. }
  405. - (nonnull NSSet *)keysWithPrefix:(nullable NSString *)prefix {
  406. __block NSMutableSet *keys = [[NSMutableSet alloc] init];
  407. dispatch_sync(_queue, ^{
  408. NSString *FQNamespace = [self fullyQualifiedNamespace:self->_FIRNamespace];
  409. if (self->_configContent.activeConfig[FQNamespace]) {
  410. NSArray *allKeys = [self->_configContent.activeConfig[FQNamespace] allKeys];
  411. if (!prefix.length) {
  412. keys = [NSMutableSet setWithArray:allKeys];
  413. } else {
  414. for (NSString *key in allKeys) {
  415. if ([key hasPrefix:prefix]) {
  416. [keys addObject:key];
  417. }
  418. }
  419. }
  420. }
  421. });
  422. return [keys copy];
  423. }
  424. #pragma mark - Defaults
  425. - (void)setDefaults:(NSDictionary<NSString *, NSObject *> *)defaultConfig {
  426. NSString *FQNamespace = [self fullyQualifiedNamespace:_FIRNamespace];
  427. NSDictionary *defaultConfigCopy = [[NSDictionary alloc] init];
  428. if (defaultConfig) {
  429. defaultConfigCopy = [defaultConfig copy];
  430. }
  431. void (^setDefaultsBlock)(void) = ^(void) {
  432. NSDictionary *namespaceToDefaults = @{FQNamespace : defaultConfigCopy};
  433. [self->_configContent copyFromDictionary:namespaceToDefaults
  434. toSource:RCNDBSourceDefault
  435. forNamespace:FQNamespace];
  436. self->_settings.lastSetDefaultsTimeInterval = [[NSDate date] timeIntervalSince1970];
  437. };
  438. dispatch_async(_queue, setDefaultsBlock);
  439. }
  440. - (FIRRemoteConfigValue *)defaultValueForKey:(NSString *)key {
  441. NSString *FQNamespace = [self fullyQualifiedNamespace:_FIRNamespace];
  442. __block FIRRemoteConfigValue *value;
  443. dispatch_sync(_queue, ^{
  444. NSDictionary *defaultConfig = self->_configContent.defaultConfig;
  445. value = defaultConfig[FQNamespace][key];
  446. if (value) {
  447. if (value.source != FIRRemoteConfigSourceDefault) {
  448. FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000002",
  449. @"Key %@ should come from source:%zd instead coming from source: %zd", key,
  450. (long)FIRRemoteConfigSourceDefault, (long)value.source);
  451. }
  452. }
  453. });
  454. return value;
  455. }
  456. - (void)setDefaultsFromPlistFileName:(nullable NSString *)fileName {
  457. if (!fileName || fileName.length == 0) {
  458. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000037",
  459. @"The plist file '%@' could not be found by Remote Config.", fileName);
  460. return;
  461. }
  462. NSArray *bundles = @[ [NSBundle mainBundle], [NSBundle bundleForClass:[self class]] ];
  463. for (NSBundle *bundle in bundles) {
  464. NSString *plistFile = [bundle pathForResource:fileName ofType:@"plist"];
  465. // Use the first one we find.
  466. if (plistFile) {
  467. NSDictionary *defaultConfig = [[NSDictionary alloc] initWithContentsOfFile:plistFile];
  468. if (defaultConfig) {
  469. [self setDefaults:defaultConfig];
  470. }
  471. return;
  472. }
  473. }
  474. FIRLogWarning(kFIRLoggerRemoteConfig, @"I-RCN000037",
  475. @"The plist file '%@' could not be found by Remote Config.", fileName);
  476. }
  477. #pragma mark - custom variables
  478. - (FIRRemoteConfigSettings *)configSettings {
  479. __block NSTimeInterval minimumFetchInterval = RCNDefaultMinimumFetchInterval;
  480. __block NSTimeInterval fetchTimeout = RCNHTTPDefaultConnectionTimeout;
  481. dispatch_sync(_queue, ^{
  482. minimumFetchInterval = self->_settings.minimumFetchInterval;
  483. fetchTimeout = self->_settings.fetchTimeout;
  484. });
  485. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000066",
  486. @"Successfully read configSettings. Minimum Fetch Interval:%f, "
  487. @"Fetch timeout: %f",
  488. minimumFetchInterval, fetchTimeout);
  489. FIRRemoteConfigSettings *settings = [[FIRRemoteConfigSettings alloc] init];
  490. settings.minimumFetchInterval = minimumFetchInterval;
  491. settings.fetchTimeout = fetchTimeout;
  492. /// The NSURLSession needs to be recreated whenever the fetch timeout may be updated.
  493. [_configFetch recreateNetworkSession];
  494. return settings;
  495. }
  496. - (void)setConfigSettings:(FIRRemoteConfigSettings *)configSettings {
  497. void (^setConfigSettingsBlock)(void) = ^(void) {
  498. if (!configSettings) {
  499. return;
  500. }
  501. self->_settings.minimumFetchInterval = configSettings.minimumFetchInterval;
  502. self->_settings.fetchTimeout = configSettings.fetchTimeout;
  503. /// The NSURLSession needs to be recreated whenever the fetch timeout may be updated.
  504. [self->_configFetch recreateNetworkSession];
  505. FIRLogDebug(kFIRLoggerRemoteConfig, @"I-RCN000067",
  506. @"Successfully set configSettings. Minimum Fetch Interval:%f, "
  507. @"Fetch timeout:%f",
  508. configSettings.minimumFetchInterval, configSettings.fetchTimeout);
  509. };
  510. dispatch_async(_queue, setConfigSettingsBlock);
  511. }
  512. @end