Firebase is back at Google I/O on May 10! Register now

Tuyên truyền cập nhật Cấu hình từ xa trong thời gian thực

Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.

Bằng cách kích hoạt chức năng nền Cấu hình từ xa được cung cấp bởi Chức năng đám mây cho Firebase cùng với FCM , bạn có thể phổ biến các bản cập nhật Cấu hình từ xa trong thời gian thực. Trong trường hợp này, bạn tạo một chức năng sẽ kích hoạt khi bạn xuất bản hoặc khôi phục mẫu Cấu hình từ xa của mình từ bảng điều khiển hoặc API. Bản cập nhật mẫu kích hoạt chức năng gửi thông báo FCM để cho khách hàng biết rằng cấu hình hiện tại của họ đã cũ và lần tìm nạp tiếp theo của họ phải từ máy chủ:

Sơ đồ hiển thị bản cập nhật Cấu hình từ xa kích hoạt cảnh báo FCM thông qua Chức năng đám mây

Phần còn lại của tài liệu này sẽ hướng dẫn bạn qua các bước này để phổ biến các bản cập nhật Cấu hình từ xa trong thời gian thực.

Đăng ký các phiên bản ứng dụng khách cho một chủ đề FCM

Để nhắm mục tiêu thông báo FCM tới một nhóm lớn các phiên bản ứng dụng khách, chẳng hạn như toàn bộ cơ sở người dùng của bạn, thông báo chủ đề là cơ chế hiệu quả nhất. Mỗi phiên bản ứng dụng sẽ nhận được các bản cập nhật Cấu hình từ xa theo thời gian thực phải đăng ký một tên chủ đề, chẳng hạn như PUSH_RC :

Nhanh

extension AppDelegate : MessagingDelegate {
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        messaging.subscribe(toTopic: "PUSH_RC") { error in
            print("Subscribed to PUSH_RC topic")
        }
    }
}
    

Mục tiêu-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");
}
    

Tạo một chức năng để gửi ping FCM khi cập nhật mẫu

Bạn có thể kích hoạt một chức năng để phản hồi các sự kiện Cấu hình từ xa, bao gồm cả việc xuất bản phiên bản cấu hình mới hoặc khôi phục về phiên bản cũ hơn. Để phổ biến các bản cập nhật mẫu trong thời gian thực, hãy tạo một hàm lắng nghe các sự kiện xuất bản mẫu, sau đó sử dụng SDK quản trị FCM từ hàm của bạn để gửi ping im lặng tới các phiên bản ứng dụng khách:

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;
  });
});

Hàm này đặt tham số CONFIG_STATE , sau đó gửi tham số đó dưới dạng tải trọng dữ liệu của thông báo FCM tới tất cả khách hàng đã đăng ký chủ đề PUSH_RC .

Đặt trạng thái Cấu hình từ xa trên máy khách

Tải trọng dữ liệu hiển thị ở bước trước luôn đặt CONFIG_STATE thành STALE trong tùy chọn chia sẻ của ứng dụng. Điều này cho biết rằng mẫu Cấu hình từ xa đã được lưu trữ trên ứng dụng hiện đã cũ do việc tạo mẫu mới, cập nhật có lần xuất bản đã kích hoạt chức năng này. Cập nhật trình xử lý thông báo của bạn để kiểm tra tình trạng này:

Nhanh

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)
}
    

Mục tiêu-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();
    }
}
    

Tìm nạp các bản cập nhật Cấu hình từ xa khi khởi động ứng dụng

Nhanh

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()
  }
}
    

Mục tiêu-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"));
                }
            });
}
    

Cuối cùng, hãy thêm logic vào ứng dụng của bạn để buộc tìm nạp Cấu hình từ xa từ mạng (bỏ qua bộ nhớ cục bộ) vì CONFIG_STATESTALE . Nếu ứng dụng của bạn tìm nạp từ mạng quá thường xuyên, thì Firebase có thể điều chỉnh ứng dụng đó. Xem Điều tiết .