開始使用 Firebase 遠端設定


您可以使用 Firebase Remote Config 在應用程式中定義參數,並在雲端更新參數值,不必發布應用程式更新,就能修改應用程式的外觀和行為。本指南將逐步說明如何開始使用,並提供一些程式碼範例,所有內容都可從 firebase/quickstart-ios GitHub 存放區複製或下載。

步驟 1:在應用程式中新增 Remote Config

  1. 如果您尚未將 Firebase 新增至 Apple 專案,請先新增。

  2. 如要Remote Config,您需使用 Google Analytics,才能條件式指定應用程式執行個體的使用者屬性和目標對象。請確認您已在專案中啟用 Google Analytics

  3. 建立單例 Remote Config 物件,如以下範例所示:

    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;

這個物件用於儲存應用程式內預設參數值、從 Remote Config 後端擷取更新的參數值,以及控制擷取的值何時可供應用程式使用。

開發期間,建議設定相對較低的最低擷取間隔。詳情請參閱節流

步驟 2:設定應用程式內預設參數值

您可以在 Remote Config 物件中設定應用程式預設參數值,讓應用程式在連線至 Remote Config 後端前正常運作,並在後端未設定任何值時提供預設值。

  1. 使用 NSDictionary 物件或 plist 檔案,定義一組參數名稱和預設參數值。

    如果您已設定 Remote Config 後端參數值,可以下載產生的 plist 檔案 (內含所有預設值),並儲存至 Xcode 專案。

    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 控制台

    1. 在「參數」分頁中,開啟「選單」,然後選取「下載預設值」

    2. 系統提示時,請啟用「iOS 的 .plist」,然後按一下「下載檔案」

  2. 使用 setDefaults: 將這些值新增至 Remote Config 物件。以下範例會從 plist 檔案設定應用程式內預設值:

    Swift

    remoteConfig.setDefaults(fromPlist: "RemoteConfigDefaults")

    Objective-C

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

步驟 3:取得要在應用程式中使用的參數值

現在您可以從 Remote Config 物件取得參數值。如果您稍後在 Remote Config 後端設定值,然後擷取並啟用這些值,應用程式就能使用這些值。否則,您會取得使用 setDefaults: 設定的應用程式內參數值。如要取得這些值,請呼叫 configValueForKey: 方法,並提供參數鍵做為引數。

let remoteConfig = RemoteConfig.remoteConfig()

// Retrieve a parameter value using configValueForKey
let welcomeMessageValue = remoteConfig.configValue(forKey: "welcome_message")
let welcomeMessage = welcomeMessageValue.stringValue

let featureFlagValue = remoteConfig.configValue(forKey: "new_feature_flag")
let isFeatureEnabled = featureFlagValue.boolValue

在 Swift 中,透過 Swift 的下標標記法存取這些值,可讀性更高且更方便:

let remoteConfig = RemoteConfig.remoteConfig()

// Retrieve a string parameter value
let welcomeMessage = remoteConfig["welcome_message"].stringValue

// Retrieve a boolean parameter value
let isFeatureEnabled = remoteConfig["new_feature_flag"].boolValue

// Retrieve a number parameter value
let maxItemCount = remoteConfig["max_items"].numberValue.intValue

使用 Codable 進行類型安全的設定

如需更複雜的設定,可以使用 Swift 的 Codable 通訊協定,從 Remote Config 解碼結構化資料。這項功能可提供型別安全設定管理,並簡化複雜物件的使用方式。

// Define a Codable struct for your configuration
struct AppFeatureConfig: Codable {
  let isNewFeatureEnabled: Bool
  let maxUploadSize: Int
  let themeColors: [String: String]
}

// Fetch and decode the configuration
func configureAppFeatures() {
  let remoteConfig = RemoteConfig.remoteConfig()
  remoteConfig.fetchAndActivate { status, error in
    guard error == nil else { return }

    do {
      let featureConfig = try remoteConfig["app_feature_config"].decoded(asType: AppFeatureConfig.self)
      configureApp(with: featureConfig)
    } catch {
      // Handle decoding errors
      print("Failed to decode configuration: \(error)")
    }
  }
}

這種做法的優點如下:

  • 定義複雜的設定結構。
  • 自動剖析 JSON 設定。
  • 存取 Remote Config 值時,請確保類型安全。
  • 提供清楚易讀的程式碼,用於處理結構化Remote Config範本。

在 SwiftUI 中使用屬性包裝函式進行宣告式設定

屬性包裝函式是強大的 Swift 功能,可讓您在屬性宣告中加入自訂行為。在 SwiftUI 中,屬性包裝函式用於管理狀態、繫結和其他屬性行為。詳情請參閱 Swift 語言指南

struct ContentView: View {
  @RemoteConfigProperty(key: "cardColor", fallback: "#f05138")
  var cardColor

  var body: some View {
    VStack {
      Text("Dynamic Configuration")
        .background(Color(hex: cardColor))
    }
    .onAppear {
      RemoteConfig.remoteConfig().fetchAndActivate()
    }
  }
}

如要在 SwiftUI 中以宣告式方式存取 Remote Config 值,並內建支援預設值和簡化設定管理,請使用 @RemoteConfigProperty 屬性包裝函式。

步驟 4:設定參數值

您可以使用 Firebase 控制台或 Remote Config 後端 API 建立新的後端預設值,根據所需的條件式邏輯或使用者指定目標,覆寫應用程式內的值。本節將逐步說明如何透過 Firebase 控制台建立這些值。

  1. Firebase 控制台中開啟專案。
  2. 選取選單中的 Remote Config,即可查看 Remote Config 資訊主頁。
  3. 定義的參數名稱必須與應用程式中定義的參數名稱相同。您可以為每個參數設定預設值 (最終會覆寫應用程式中的預設值),也可以設定條件值。詳情請參閱「Remote Config參數和條件」。
  4. 如果使用自訂信號條件,請定義屬性和屬性值。下列範例說明如何定義自訂信號條件。

    Swift

      Task {
          let customSignals: [String: CustomSignalValue?] = [
          "city": .string("Tokyo"),
          "preferred_event_category": .string("sports")
        ]
    
        do {
          try await remoteConfig.setCustomSignals(customSignals)
          print("Custom signals set successfully!")
          } catch {
              print("Error setting custom signals: \(error)")
          }
    }

    Objective-C

      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSDictionary *customSignals = @{
          @"city": @"Tokyo",
          @"preferred_event_category": @"sports"
        };
    
        [self.remoteConfig setCustomSignals:customSignals withCompletion:^(NSError * _Nullable error) {
            if (error) {
                NSLog(@"Error setting custom signals: %@", error);
            } else {
                NSLog(@"Custom signals set successfully!");
            }
      }];
    });

步驟 5:擷取並啟用值

如要從 Remote Config 擷取參數值,請呼叫 fetchWithCompletionHandler:fetchWithExpirationDuration:completionHandler: 方法。系統會擷取您在後端設定的所有值,並快取至 Remote Config 物件。

如要透過一次呼叫擷取及啟用值,請使用 fetchAndActivateWithCompletionHandler:

這個範例會從 Remote Config 後端 (非快取值) 擷取值,並呼叫 activateWithCompletionHandler:,讓應用程式可以使用這些值:

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

由於這些更新後的參數值會影響應用程式的行為和外觀,因此您應在確保使用者體驗不受影響的時間點啟用擷取的值,例如使用者下次開啟應用程式時。如需更多資訊和範例,請參閱「遠端設定載入策略」。

步驟 6:即時收聽最新資訊

擷取參數值後,您可以使用即時 Remote Config 監聽 Remote Config 後端的更新。有更新時,系統會向連線裝置傳送即時Remote Config信號,並在您發布新Remote Config版本後自動擷取變更。

Firebase SDK for Apple 平台 10.7.0 以上版本支援即時更新。

  1. 在應用程式中呼叫 addOnConfigUpdateListener,開始監聽更新,並自動擷取任何新的或更新的參數值。下列範例會監聽更新,並在呼叫 activateWithCompletionHandler 時,使用新擷取的值顯示更新的歡迎訊息。

    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. 下次發布新版 Remote Config 時,執行應用程式並監聽變更的裝置會呼叫完成處理常式。

調節

如果應用程式在短時間內擷取過多資料,系統會限制擷取呼叫,且 SDK 會傳回 FIRRemoteConfigFetchStatusThrottled。在 6.3.0 之前的 SDK 版本中,60 分鐘內最多只能發出 5 個擷取要求 (新版限制較寬鬆)。

在應用程式開發期間,您可能需要更頻繁地擷取資料,以非常頻繁地重新整理快取 (每小時多次),以便在開發及測試應用程式時快速疊代。當伺服器上的設定更新時,即時遠端設定更新會自動略過快取。如要配合多位開發人員快速疊代專案,您可以在應用程式中暫時新增 FIRRemoteConfigSettings 屬性,並將最低擷取間隔設為較短的時間 (MinimumFetchInterval)。

Remote Config 的預設和建議生產擷取間隔為 12 小時,這表示無論實際發出多少擷取呼叫,系統都不會在 12 小時內從後端擷取設定超過一次。具體來說,系統會依下列順序決定最短擷取間隔:

  1. fetch(long) 中的參數
  2. FIRRemoteConfigSettings.MinimumFetchInterval 中的參數
  3. 預設值為 12 小時

後續步驟

如果您尚未探索Remote Config 應用情境,請參閱一些重要概念和進階策略說明文件,包括: