FCMとともにCloud Functions for Firebaseによって提供される Remote Config バックグラウンド関数トリガーを使用すると、Remote Config の更新をリアルタイムで伝達できます。このシナリオでは、Remote Config テンプレートをダッシュボードまたは API から公開またはロールバックするときにトリガーされる関数を作成します。テンプレートの更新により、FCM メッセージを送信する関数がトリガーされ、クライアントに既存の構成が古く、次の取得はサーバーから行う必要があることが通知されます。
このドキュメントの残りの部分では、これらの手順を順を追って説明し、Remote Config の更新をリアルタイムで伝達します。
クライアント アプリ インスタンスを FCM トピックにサブスクライブする
ユーザー ベース全体など、クライアント アプリ インスタンスの大規模なグループに FCM メッセージを送信するには、トピック メッセージングが最も効率的なメカニズムです。リアルタイムの Remote Config 更新を受信する各アプリ インスタンスは、 PUSH_RC
などのトピック名にサブスクライブする必要があります。
迅速
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"); }]; }
アンドロイド
@Override public void onNewToken(String s) { FirebaseMessaging.getInstance().subscribeToTopic("PUSH_RC"); }
テンプレートの更新時に FCM ping を送信する関数を作成する
新しい構成バージョンの公開や古いバージョンへのロールバックなど、Remote Config イベントに応答して関数をトリガーできます。テンプレートの更新をリアルタイムで伝達するには、テンプレートの発行イベントをリッスンする関数を作成し、関数から FCM Admin SDK を使用してクライアント アプリ インスタンスにサイレント ping を送信します。
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; }); });
この関数はCONFIG_STATE
パラメーターを設定し、それを FCM メッセージのデータ ペイロードとして、 PUSH_RC
トピックにサブスクライブしているすべてのクライアントに送信します。
クライアントで Remote Config の状態を設定する
前の手順で示したデータ ペイロードは、アプリの共有設定で常にCONFIG_STATE
をSTALE
に設定します。これは、アプリに既に保存されている Remote Config テンプレートが、発行によって関数がトリガーされた新しい更新されたテンプレートが作成されたため、古くなったことを示しています。通知ハンドラーを更新して、この条件をテストします。
迅速
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); }
アンドロイド
@Override public void onMessageReceived(RemoteMessage remoteMessage) { if (remoteMessage.getData().containsKey("CONFIG_STATE")) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); sharedPreferences.edit().putBoolean("CONFIG_STALE", true).apply(); } }
アプリの起動時に Remote Config の更新を取得する
迅速
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]; }]; }
アンドロイド
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")); } }); }
最後に、 CONFIG_STATE
がSTALE
であるため、ネットワークから (ローカル ストレージを無視して) Remote Config フェッチを強制するロジックをアプリに追加します。アプリがネットワークからフェッチする頻度が高すぎると、Firebase によってスロットリングされる可能性があります。スロットリングを参照してください。