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

開始使用 Firebase 遠程配置

透過集合功能整理內容 你可以依據偏好儲存及分類內容。


您可以使用 Firebase Remote Config 在您的應用程序中定義參數並在雲端更新它們的值,從而允許您修改應用程序的外觀和行為而無需分發應用程序更新。本指南將引導您完成入門步驟並提供一些示例代碼,所有這些代碼都可以從firebase/quickstart-ios GitHub 存儲庫中克隆或下載。

第 1 步:將遠程配置添加到您的應用

  1. 安裝適用於 Apple 平台的 Firebase SDK

  2. 創建單例遠程配置對象,如以下示例所示:

    迅速

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

    目標-C

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

此對像用於存儲應用內默認參數值、從遠程配置後端獲取更新的參數值,以及控制何時將獲取的值提供給您的應用。

在開發過程中,建議設置一個相對較低的最小獲取間隔。有關詳細信息,請參閱節流

第 2 步:設置應用內默認參數值

您可以在 Remote Config 對像中設置應用內默認參數值,以便您的應用在連接到 Remote Config 後端之前按預期運行,並且如果沒有在後端設置默認值,則默認值可用。

  1. 使用NSDictionary對像或plist 文件定義一組參數名稱和默認參數值。

    如果您已經配置了 Remote Config 後端參數值,您可以下載包含所有默認值的生成的plist文件並將其保存到您的 Xcode 項目中。

    休息

    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
    

    Firebase 控制台

    1. Parameters選項卡中,打開 Menu ,然後選擇Download default values

    2. 出現提示時,為 iOS 啟用 .plist ,然後單擊下載文件

  2. 使用setDefaults:將這些值添加到遠程配置對象。以下示例從 plist 文件設置應用內默認值:

    迅速

    remoteConfig.setDefaults(fromPlist: "RemoteConfigDefaults")

    目標-C

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

第 3 步:獲取要在您的應用中使用的參數值

現在您可以從 Remote Config 對像中獲取參數值。如果您稍後在 Remote Config 後端設置值,獲取它們,然後激活它們,這些值將對您的應用可用。否則,您將獲得使用setDefaults:配置的應用內參數值。要獲取這些值,請調用configValueForKey:方法,提供參數鍵作為參數。

第 4 步:設置參數值

使用 Firebase 控制台或遠程配置後端 API ,您可以創建新的後端默認值,根據所需的條件邏輯或用戶定位覆蓋應用內值。本部分將引導您完成 Firebase 控制台步驟以創建這些值。

  1. Firebase 控制台中,打開您的項目。
  2. 從菜單中選擇遠程配置以查看遠程配置儀表板。
  3. 使用與您在應用程序中定義的參數相同的名稱定義參數。對於每個參數,您可以設置一個默認值(最終將覆蓋應用內的默認值),您還可以設置條件值。要了解更多信息,請參閱遠程配置參數和條件

第 5 步:獲取並激活值

要從遠程配置中獲取參數值,請調用fetchWithCompletionHandler:fetchWithExpirationDuration:completionHandler:方法。您在後端設置的任何值都將被提取並緩存在遠程配置對像中。

對於希望在一次調用中獲取和激活值的情況,請使用fetchAndActivateWithCompletionHandler:

此示例從 Remote Config 後端獲取值(不是緩存的值)並調用activateWithCompletionHandler:使它們對應用程序可用:

迅速

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

目標-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);
    }
}];

由於這些更新的參數值會影響應用的行為和外觀,因此您應該在確保用戶流暢體驗的時間激活獲取的值,例如用戶下次打開您的應用時。有關更多信息和示例,請參閱遠程配置加載策略

節流

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

下一步

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:

,


You can use Firebase Remote Config to define parameters in your app and update their values in the cloud, allowing you to modify the appearance and behavior of your app without distributing an app update. This guide walks you through the steps to get started and provides some sample code, all of which is available to clone or download from the firebase/quickstart-ios GitHub repository.

Step 1: Add Remote Config to your app

  1. Install the Firebase SDK for Apple platforms.

  2. Create the singleton Remote Config object, as shown in the following example:

    Swift

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

    Objective-C

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

This object is used to store in-app default parameter values, fetch updated parameter values from the Remote Config backend, and control when fetched values are made available to your app.

During development, it's recommended to set a relatively low minimum fetch interval. See Throttling for more information.

Step 2: Set in-app default parameter values

You can set in-app default parameter values in the Remote Config object, so that your app behaves as intended before it connects to the Remote Config backend, and so that default values are available if none are set in the backend.

  1. Define a set of parameter names, and default parameter values using an NSDictionary object or a plist file .

    If you have already configured Remote Config backend parameter values, you can download a generated plist file that includes all default values and save it to your Xcode project.

    REST

    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
    

    Firebase console

    1. In the Parameters tab, open the Menu , and select Download default values .

    2. When prompted, enable .plist for iOS , then click Download file .

  2. Add these values to the Remote Config object using setDefaults: . The following example sets in-app default values from a plist file:

    Swift

    remoteConfig.setDefaults(fromPlist: "RemoteConfigDefaults")

    Objective-C

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

Step 3: Get parameter values to use in your app

Now you can get parameter values from the Remote Config object. If you later set values in the Remote Config backend, fetch them, and then activate them, those values are available to your app. Otherwise, you get the in-app parameter values configured using setDefaults: . To get these values, call the configValueForKey: method, providing the parameter key as an argument.

Step 4: Set parameter values

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.

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

下一步

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: