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

Bắt đầu với Cấu hình từ xa Firebase

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ạn có thể sử dụng Cấu hình từ xa Firebase để xác định các tham số trong ứng dụng của mình và cập nhật giá trị của chúng trong đám mây, cho phép bạn sửa đổi giao diện và hành vi của ứng dụng mà không cần phân phối bản cập nhật ứng dụng. Hướng dẫn này hướng dẫn bạn qua các bước để bắt đầu và cung cấp một số mã mẫu, tất cả đều có sẵn để sao chép hoặc tải xuống từ kho lưu trữ firebase/quickstart-ios GitHub.

Bước 1: Thêm Remote Config vào ứng dụng của bạn

  1. Cài đặt SDK Firebase cho các nền tảng của Apple.

  2. Tạo đối tượng Cấu hình Từ xa đơn lẻ, như minh họa trong ví dụ sau:

    Nhanh

    remoteConfig = RemoteConfig.remoteConfig()
    let settings = RemoteConfigSettings()
    settings.minimumFetchInterval = 0
    remoteConfig.configSettings = settings

    Mục tiêu-C

    self.remoteConfig = [FIRRemoteConfig remoteConfig];
    FIRRemoteConfigSettings *remoteConfigSettings = [[FIRRemoteConfigSettings alloc] init];
    remoteConfigSettings.minimumFetchInterval = 0;
    self.remoteConfig.configSettings = remoteConfigSettings;

Đối tượng này được sử dụng để lưu trữ các giá trị thông số mặc định trong ứng dụng, tìm nạp các giá trị thông số được cập nhật từ chương trình phụ trợ Cấu hình từ xa và kiểm soát thời điểm các giá trị đã tìm nạp được cung cấp cho ứng dụng của bạn.

Trong quá trình phát triển, bạn nên đặt khoảng thời gian tìm nạp tối thiểu tương đối thấp. Xem Throttling để biết thêm thông tin.

Bước 2: Đặt giá trị thông số mặc định trong ứng dụng

Bạn có thể đặt các giá trị tham số mặc định trong ứng dụng trong đối tượng Cấu hình từ xa để ứng dụng của bạn hoạt động như dự kiến ​​trước khi kết nối với phần phụ trợ Cấu hình từ xa và để các giá trị mặc định khả dụng nếu không có giá trị nào được đặt trong phần phụ trợ.

  1. Xác định một tập hợp tên tham số và giá trị tham số mặc định bằng cách sử dụng đối tượng NSDictionary hoặc tệp plist .

    Nếu bạn đã định cấu hình các giá trị tham số phụ trợ Cấu hình từ xa, bạn có thể tải xuống tệp plist được tạo bao gồm tất cả các giá trị mặc định và lưu tệp đó vào dự án Xcode của bạn.

    NGHỈ NGƠI

    curl --compressed -D headers -H "Authorization: Bearer token -X GET https://firebaseremoteconfig.googleapis.com/v1/projects/my-project-id/remoteConfig:downloadDefaults?format=PLIST -o RemoteConfigDefaults.plist
    

    Bảng điều khiển căn cứ hỏa lực

    1. Trong tab Tham số , mở Menu và chọn Tải xuống các giá trị mặc định .

    2. Khi được nhắc, hãy bật .plist cho iOS , sau đó nhấp vào Tải xuống tệp .

  2. Thêm các giá trị này vào đối tượng Cấu hình từ xa bằng cách sử dụng setDefaults: . Ví dụ sau đặt giá trị mặc định trong ứng dụng từ tệp plist:

    Nhanh

    remoteConfig.setDefaults(fromPlist: "RemoteConfigDefaults")

    Mục tiêu-C

    [self.remoteConfig setDefaultsFromPlistFileName:@"RemoteConfigDefaults"];

Bước 3: Nhận các giá trị tham số để sử dụng trong ứng dụng của bạn

Bây giờ bạn có thể lấy các giá trị tham số từ đối tượng Cấu hình từ xa. Nếu sau này bạn đặt các giá trị trong phần phụ trợ Cấu hình từ xa, hãy tìm nạp chúng rồi kích hoạt chúng, thì những giá trị đó sẽ có sẵn cho ứng dụng của bạn. Nếu không, bạn sẽ nhận được các giá trị thông số trong ứng dụng được định cấu hình bằng cách sử dụng setDefaults: . Để nhận các giá trị này, hãy gọi phương thức configValueForKey: cung cấp khóa tham số làm đối số.

Bước 4: Đặt giá trị tham số

Using the Firebase console or the Remote Config backend APIs , you can create new backend default values that override the in-app values according to your desired conditional logic or user targeting. This section walks you through the Firebase console steps to create these values.

  1. In the Firebase console , open your project.
  2. Select Remote Config from the menu to view the Remote Config dashboard.
  3. Define parameters with the same names as the parameters that you defined in your app. For each parameter, you can set a default value (which will eventually override the in-app default value) and you can also set conditional values. To learn more, see Remote Config Parameters and Conditions .

Step 5: Fetch and activate values

To fetch parameter values from Remote Config, call the fetchWithCompletionHandler: or fetchWithExpirationDuration:completionHandler: method. Any values that you set on the backend are fetched and cached in the Remote Config object.

For cases where you want to fetch and activate values in one call, use fetchAndActivateWithCompletionHandler: .

This example fetches values from the Remote Config backend (not cached values) and calls activateWithCompletionHandler: to make them available to the app:

Swift

remoteConfig.fetch { (status, error) -> Void in
  if status == .success {
    print("Config fetched!")
    self.remoteConfig.activate { changed, error in
      // ...
    }
  } else {
    print("Config not fetched")
    print("Error: \(error?.localizedDescription ?? "No error available.")")
  }
  self.displayWelcome()
}

Objective-C

[self.remoteConfig fetchWithCompletionHandler:^(FIRRemoteConfigFetchStatus status, NSError *error) {
    if (status == FIRRemoteConfigFetchStatusSuccess) {
        NSLog(@"Config fetched!");
      [self.remoteConfig activateWithCompletion:^(BOOL changed, NSError * _Nullable error) {
        if (error != nil) {
          NSLog(@"Activate error: %@", error.localizedDescription);
        } else {
          dispatch_async(dispatch_get_main_queue(), ^{
            [self displayWelcome];
          });
        }
      }];
    } else {
        NSLog(@"Config not fetched");
        NSLog(@"Error %@", error.localizedDescription);
    }
}];

Because these updated parameter values affect the behavior and appearance of your app, you should activate the fetched values at a time that ensures a smooth experience for your user, such as the next time that the user opens your app. See Remote Config loading strategies for more information and examples.

Step 6: Listen for updates in real time

After you fetch parameter values, you can use real-time Remote Config to listen for updates from the Remote Config backend. Real-time Remote Config signals to connected devices when updates are available and automatically fetches the changes after you publish a new Remote Config version.

  1. In your app, call addOnConfigUpdateListener to start listening for updates and automatically fetch any new or updated parameter values. The following example listens for updates and when activateWithCompletionHandler is called, uses the newly fetched values to display an updated welcome message.

    Swift

    remoteConfig.addOnConfigUpdateListener { configUpdate, error in
      guard let configUpdate, error == nil else {
        print("Error listening for config updates: \(error)")
      }
    
      print("Updated keys: \(configUpdate.updatedKeys)")
    
      self.remoteConfig.activate { changed, error in
        guard error == nil else { return self.displayError(error) }
        DispatchQueue.main.async {
          self.displayWelcome()
        }
      }
    }
    

    Objective-C

    __weak __typeof__(self) weakSelf = self;
    [self.remoteConfig addOnConfigUpdateListener:^(FIRRemoteConfigUpdate * _Nonnull configUpdate, NSError * _Nullable error) {
      if (error != nil) {
        NSLog(@"Error listening for config updates %@", error.localizedDescription);
      } else {
        NSLog(@"Updated keys: %@", configUpdate.updatedKeys);
    
        __typeof__(self) strongSelf = weakSelf;
        [strongSelf.remoteConfig activateWithCompletion:^(BOOL changed, NSError * _Nullable error) {
          if (error != nil) {
            NSLog(@"Activate error %@", error.localizedDescription);
          }
    
          dispatch_async(dispatch_get_main_queue(), ^{
            [strongSelf displayWelcome];
          });
        }];
      }
    }];
    
  2. The next time you publish a new version of your Remote Config, devices that are running your app and listening for changes will call the completion handler.

Throttling

If an app fetches too many times in a short time period, fetch calls are throttled and the SDK returns FIRRemoteConfigFetchStatusThrottled . Before SDK version 6.3.0, the limit was 5 fetch requests in a 60 minute window (newer versions have more permissive limits).

During app development, you might want to refresh the cache very frequently (many times per hour) to let you rapidly iterate as you develop and test your app. To accommodate rapid iteration on a project with numerous developers, you can temporarily add a FIRRemoteConfigSettings property with a low minimum fetch interval ( MinimumFetchInterval ) in your app.

The default and recommended production fetch interval for Remote Config is 12 hours, which means that configs won't be fetched from the backend more than once in a 12 hour window, regardless of how many fetch calls are actually made. Specifically, the minimum fetch interval is determined in this following order:

  1. The parameter in fetch(long)
  2. The parameter in FIRRemoteConfigSettings.MinimumFetchInterval
  3. The default value of 12 hours

Next steps

If you haven't already, explore the Remote Config use cases , and take a look at some of the key concepts and advanced strategies documentation, including: