Utilizzando l'attivazione della funzione in background di Remote Config fornita da Cloud Functions for Firebase insieme a FCM , puoi propagare gli aggiornamenti di Remote Config in tempo reale. In questo scenario, crei una funzione che si attiva quando pubblichi o esegui il rollback del modello Remote Config dal dashboard o dall'API. L'aggiornamento del modello attiva la funzione per inviare un messaggio FCM per far sapere ai client che la loro configurazione esistente è obsoleta e che il recupero successivo dovrebbe provenire dal server:
Il resto di questo documento ti guida attraverso questi passaggi per propagare gli aggiornamenti di Remote Config in tempo reale.
Sottoscrivi le istanze dell'app client a un argomento FCM
Per indirizzare un messaggio FCM a un ampio gruppo di istanze dell'app client come l'intera base di utenti, la messaggistica dell'argomento è il meccanismo più efficiente. Ogni istanza dell'app che dovrebbe ricevere gli aggiornamenti di Remote Config in tempo reale deve sottoscrivere un nome di argomento come, ad esempio, PUSH_RC
:
Rapido
extension AppDelegate : MessagingDelegate { func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) { messaging.subscribe(toTopic: "PUSH_RC") { error in print("Subscribed to PUSH_RC topic") } } }
Obiettivo-C
- (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken { [[FIRMessaging messaging] subscribeToTopic:@"PUSH_RC" completion:^(NSError * _Nullable error) { NSLog(@"Subscribed to PUSH_RC topic"); }]; }
Androide
@Override public void onNewToken(String s) { FirebaseMessaging.getInstance().subscribeToTopic("PUSH_RC"); }
Crea una funzione per inviare un ping FCM sugli aggiornamenti del modello
È possibile attivare una funzione in risposta agli eventi Remote Config, inclusa la pubblicazione di una nuova versione di configurazione o il rollback a una versione precedente. Per propagare gli aggiornamenti del modello in tempo reale, crea una funzione che ascolti gli eventi di pubblicazione del modello, quindi usa FCM Admin SDK dalla tua funzione per inviare un ping silenzioso alle istanze dell'app client:
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; }); });
Questa funzione imposta un parametro CONFIG_STATE
, quindi lo invia come payload di dati di un messaggio FCM a tutti i client iscritti all'argomento PUSH_RC
.
Impostare lo stato Remote Config sul client
Il payload dei dati mostrato nel passaggio precedente imposta sempre CONFIG_STATE
su STALE
nelle preferenze condivise dell'app. Ciò indica che il modello Remote Config già memorizzato nell'app è ora obsoleto a causa della creazione del nuovo modello aggiornato la cui pubblicazione ha attivato la funzione. Aggiorna il gestore delle notifiche per verificare questa condizione:
Rapido
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) }
Obiettivo-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); }
Androide
@Override public void onMessageReceived(RemoteMessage remoteMessage) { if (remoteMessage.getData().containsKey("CONFIG_STATE")) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); sharedPreferences.edit().putBoolean("CONFIG_STALE", true).apply(); } }
Recupera gli aggiornamenti di Remote Config all'avvio dell'app
Rapido
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() } }
Obiettivo-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]; }]; }
Androide
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")); } }); }
Infine, aggiungi la logica alla tua app per forzare un recupero della configurazione remota dalla rete (ignorando l'archiviazione locale) perché CONFIG_STATE
è STALE
. Se la tua app viene recuperata dalla rete troppo frequentemente, potrebbe essere limitata da Firebase. Vedere limitazione .