Using the Remote Config background function triggering provided by Cloud Functions for Firebase along with FCM, you can propagate Remote Config updates in real time. In this scenario, you create a function that triggers when you publish or roll back your Remote Config template from the dashboard or the API. The template update triggers the function to send an FCM message to let clients know that their existing config is stale and that their next fetch should be from the server:
The rest of this document walks you through these steps to propagate Remote Config updates in real time.
Subscribe client app instances to an FCM topic
For targeting an FCM message to a large group of client app instances
such as your entire user base, topic messaging is the most efficient mechanism.
Each app instance that should receive realtime Remote Config updates must
subscribe to a topic name like, for example, PUSH_RC
:
Swift
extension AppDelegate : MessagingDelegate { func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) { messaging.subscribe(toTopic: "PUSH_RC") { error in print("Subscribed to PUSH_RC topic") } } }
Objective-C
- (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken { [[FIRMessaging messaging] subscribeToTopic:@"PUSH_RC" completion:^(NSError * _Nullable error) { NSLog(@"Subscribed to PUSH_RC topic"); }]; }
Android
@Override public void onNewToken(String s) { FirebaseMessaging.getInstance().subscribeToTopic("PUSH_RC"); }
Create a function to send an FCM ping on template updates
You can trigger a function in response to Remote Config events, including the publication of a new config version or the rollback to an older version. To propagate template updates in real time, create a function that listens for template publication events, and then use the FCM Admin SDK from your function to send a silent ping to client app instances:
exports.pushConfig = functions.remoteConfig.onUpdate(versionMetadata => { // Create FCM payload to send data message to PUSH_RC topic. const payload = { topic: "PUSH_RC", data: { "CONFIG_STATE": "STALE" } }; // Use the Admin SDK to send the ping via FCM. return admin.messaging().send(payload).then(resp => { console.log(resp); return null; }); });
This function sets a CONFIG_STATE
parameter, and then sends that as the data
payload of an FCM message to all clients subscribed to the PUSH_RC
topic.
Set the Remote Config state on the client
The data payload shown in the previous step always sets CONFIG_STATE
to
STALE
in the app's shared preferences. This indicates that the Remote Config
template already stored on the app is now stale due the creation of the new,
updated template whose publication triggered the function. Update your
notification handler to test for this condition:
Swift
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { if (userInfo.index(forKey: "CONFIG_STATE") != nil) { print("Config set to stale") UserDefaults.standard.set(true, forKey:"CONFIG_STALE") } completionHandler(UIBackgroundFetchResult.newData) }
Objective-C
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { if (userInfo[@"CONFIG_STATE"]) { NSLog(@"Config set to stale"); [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"CONFIG_STALE"]; } completionHandler(UIBackgroundFetchResultNewData); }
Android
@Override public void onMessageReceived(RemoteMessage remoteMessage) { if (remoteMessage.getData().containsKey("CONFIG_STATE")) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); sharedPreferences.edit().putBoolean("CONFIG_STALE", true).apply(); } }
Fetch the Remote Config updates on app startup
Swift
func fetchConfig() { welcomeLabel.text = remoteConfig[loadingPhraseConfigKey].stringValue var expirationDuration = 3600 // If your app is using developer mode, expirationDuration is set to 0, so each fetch will // retrieve values from the service. if remoteConfig.configSettings.isDeveloperModeEnabled || UserDefaults.standard.bool(forKey: "CONFIG_STALE") { expirationDuration = 0 } remoteConfig.fetch(withExpirationDuration: TimeInterval(expirationDuration)) { (status, error) -> Void in if status == .success { print("Config fetched!") self.remoteConfig.activateFetched() } else { print("Config not fetched") print("Error: \(error?.localizedDescription ?? "No error available.")") } self.displayWelcome() } }
Objective-C
- (void)fetchConfig { self.welcomeLabel.text = self.remoteConfig[kLoadingPhraseConfigKey].stringValue; long expirationDuration = 3600; // If your app is using developer mode, expirationDuration is set to 0, so each fetch will // retrieve values from the Remote Config service. if (self.remoteConfig.configSettings.isDeveloperModeEnabled || [[NSUserDefaults standardUserDefaults] boolForKey:@"CONFIG_STALE"]) { expirationDuration = 0; } [self.remoteConfig fetchWithExpirationDuration:expirationDuration completionHandler:^(FIRRemoteConfigFetchStatus status, NSError *error) { if (status == FIRRemoteConfigFetchStatusSuccess) { NSLog(@"Config fetched!"); [self.remoteConfig activateFetched]; [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"CONFIG_STALE"]; } else { NSLog(@"Config not fetched"); NSLog(@"Error %@", error.localizedDescription); } [self displayWelcome]; }]; }
Android
private void fetchWelcomeMessage() { mWelcomeTextView.setText(mFirebaseRemoteConfig.getString("loading_phrase")); long cacheExpiration = 43200; // 12 hours in seconds. // If your app is using developer mode or cache is stale, cacheExpiration is set to 0, // so each fetch will retrieve values from the service. if (mFirebaseRemoteConfig.getInfo().getConfigSettings().isDeveloperModeEnabled() || mSharedPreferences.getBoolean("CONFIG_STALE", false)) { cacheExpiration = 0; } mFirebaseRemoteConfig.fetch(cacheExpiration) .addOnCompleteListener(this, new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Toast.makeText(MainActivity.this, "Fetch Succeeded", Toast.LENGTH_SHORT).show(); // After config data is successfully fetched, it must be activated before newly fetched // values are returned. mFirebaseRemoteConfig.activateFetched(); } else { Toast.makeText(MainActivity.this, "Fetch Failed", Toast.LENGTH_SHORT).show(); } mWelcomeTextView.setText(mFirebaseRemoteConfig.getString("welcome_message")); } }); }
Finally, add logic to your app to force a Remote Config fetch from
the network (ignoring local storage) because CONFIG_STATE
is STALE
.
If your app fetches from the network too frequently, it may be throttled by
Firebase. See Throttling.