設定多項專案

本頁面將說明如何在應用程式中使用多個 Firebase 專案。

許多應用程式只需要一個 Firebase 專案和預設設定即可 入門指南。適用時機範例 使用多項 Firebase 專案的做法如下:

  • 設定開發環境以使用其他 Firebase 專案 建立 AI 流量
  • 在應用程式中存取多項 Firebase 專案中的內容。

支援不同的環境

其中一個常見的用途是支援獨立的 Firebase 專案,以便執行開發作業 和正式環境

Web 和 Admin SDK 是由 並將值傳遞至其初始化函式。針對這些 SDK,您可以使用 以便選取開發或正式環境設定變數。

Android 和 Apple 平台 (以及其 Unity 和 C++ 包裝函式) 通常會載入 設定檔設定:Apple 上的「GoogleService-Info.plist」 以及 Android 上的 google-services.json這類檔案會讀取為 參照選項物件 (FIROptionFirebaseOptions) Firebase 應用程式物件 (FIRAppFirebaseApp)。

對這些平台切換環境時,通常都會以 建構時間決定,方法是為每個專案使用不同的設定檔 環境。

在 Apple 應用程式中支援多種環境

根據預設,FirebaseApp.configure() 會載入 GoogleService-Info.plist 檔案 並未隨附應用程式如果您的開發環境和實際工作環境 已在 Xcode 中被設定為個別目標,您可以:

  • 下載兩個 GoogleService-Info.plist 檔案
  • 將兩個檔案儲存在不同的目錄中
  • 同時將兩者新增至 Xcode 專案
  • 使用目標將不同檔案與不同目標建立關聯 成員資格面板:

目標成員資格面板

如果建構作業是單一目標的一部分,最好的做法是同時提供 不重複的設定檔名稱 (例如 GoogleService-Info-Free.plistGoogleService-Info-Paid.plist)。然後在執行階段選擇要載入的 Plist。 例如:

// Load a named file.
let filePath = Bundle.main.path(forResource: "MyGoogleService", ofType: "plist")
guard let fileopts = FirebaseOptions(contentsOfFile: filePath!)
  else { assert(false, "Couldn't load config file") }
FirebaseApp.configure(options: fileopts)

在 Android 應用程式中支援多個環境

在 Android 中,google-services.json 檔案會處理成 Android 字串 透過 Google Services Gradle 外掛程式 檢查資源配置您可以看到 Google Service 外掛程式說明文件中 處理 JSON 檔案

您可以擁有多個不同用途的 google-services.json 檔案 建構變數 方法是將 google-services.json 檔案放在每個 在應用程式模組根目錄下開啟變化版本。舉例來說,假設您有「Develop」(開發)和 「release」建構版本,您的設定可按照以下方式整理:

app/
    google-services.json
    src/development/google-services.json
    src/release/google-services.json
    ...

詳情請參閱 新增 JSON 檔案

接著 FirebaseInitProvider、 可在應用程式程式碼之前執行, 這些值。

因為這個供應器只會讀取已知名稱的資源 您可以選擇直接將字串資源新增至應用程式 安裝 Google 服務 Gradle 外掛程式方法如下:

  • 從根層級 build.gradle 中移除 google-services 外掛程式
  • 從專案中刪除 google-services.json
  • 直接新增字串資源
  • 正在從「build.gradle」應用程式中刪除「apply plugin: 'com.google.gms.google-services'

在應用程式中使用多個專案

有時候,您會需要使用相同的 API 存取不同專案, 例如存取多個資料庫執行個體在大多數情況下 Firebase 應用程式物件,用於管理所有 Firebase 的設定 相互整合此物件已作為正常設定的一部分進行初始化。不過, 如要從單一應用程式存取多項專案,您必須具備 不同的 Firebase 應用程式物件,以便個別參照每個物件。是 以便初始化其他執行個體。

無論是哪一種情況,您都需要先建立 Firebase 選項物件來存放 設定資料。完整說明文件 請參閱 類別:

畫面顯示在應用程式中使用這些類別來支援多項專案 下列範例:

Swift

// Configure with manual options. Note that projectID and apiKey, though not
// required by the initializer, are mandatory.
let secondaryOptions = FirebaseOptions(googleAppID: "1:27992087142:ios:2a4732a34787067a",
                                       gcmSenderID: "27992087142")
secondaryOptions.apiKey = "AIzaSyBicqfAZPvMgC7NZkjayUEsrepxuXzZDsk"
secondaryOptions.projectID = "projectid-12345"

// The other options are not mandatory, but may be required
// for specific Firebase products.
secondaryOptions.bundleID = "com.google.firebase.devrel.FiroptionConfiguration"
secondaryOptions.trackingID = "UA-12345678-1"
secondaryOptions.clientID = "27992087142-ola6qe637ulk8780vl8mo5vogegkm23n.apps.googleusercontent.com"
secondaryOptions.databaseURL = "https://myproject.firebaseio.com"
secondaryOptions.storageBucket = "myproject.appspot.com"
secondaryOptions.androidClientID = "12345.apps.googleusercontent.com"
secondaryOptions.deepLinkURLScheme = "myapp://"
secondaryOptions.storageBucket = "projectid-12345.appspot.com"
secondaryOptions.appGroupID = nil

Kotlin+KTX

// Manually configure Firebase Options. The following fields are REQUIRED:
//   - Project ID
//   - App ID
//   - API Key
val options = FirebaseOptions.Builder()
    .setProjectId("my-firebase-project")
    .setApplicationId("1:27992087142:android:ce3b6448250083d1")
    .setApiKey("AIzaSyADUe90ULnQDuGShD9W23RDP0xmeDc6Mvw")
    // .setDatabaseUrl(...)
    // .setStorageBucket(...)
    .build()

Java

// Manually configure Firebase Options. The following fields are REQUIRED:
//   - Project ID
//   - App ID
//   - API Key
FirebaseOptions options = new FirebaseOptions.Builder()
        .setProjectId("my-firebase-project")
        .setApplicationId("1:27992087142:android:ce3b6448250083d1")
        .setApiKey("AIzaSyADUe90ULnQDuGShD9W23RDP0xmeDc6Mvw")
        // setDatabaseURL(...)
        // setStorageBucket(...)
        .build();

Web

// The following fields are REQUIRED:
//  - Project ID
//  - App ID
//  - API Key
const secondaryAppConfig = {
    projectId: "<PROJECT_ID>",
    appId: "<APP_ID>",
    apiKey: "<API_KEY>",
    // databaseURL: "...",
    // storageBucket: "...",
};

C++

firebase::AppOptions secondary_app_options;

// API key, app ID, and project ID are always required.
secondary_app_options.set_api_key("<API_KEY>");
secondary_app_options.set_app_id("<GOOGLE_APP_ID>");
secondary_app_options.set_project_id("<PROJECT_ID>");

// The following options are specific to individual Firebase products
// and may not always be required.
secondary_app_options.set_database_url("<DATABASE_URL>");
secondary_app_options.set_messaging_sender_id("<SENDER_ID>");
secondary_app_options.set_storage_bucket("<STORAGE_BUCKET>");

Unity

Firebase.AppOptions secondaryAppOptions = new Firebase.AppOptions {
  ApiKey = "<API_KEY>",
  AppId = "<GOOGLE_APP_ID>",
  ProjectId = "<PROJECT_ID>"
};

Node.js

const secondaryServiceAccount = require('./path/to/serviceAccountKey.json');

// All required options are specified by the service account,
// add service-specific configuration like databaseURL as needed.
const secondaryAppConfig = {
    credential: cert(secondaryServiceAccount),
    // databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
};

Java

FileInputStream serviceAccount = new FileInputStream("path/to/serviceAccountKey.json");

FirebaseOptions secondaryAppConfig = new FirebaseOptions.Builder()
  .setCredential(FirebaseCredentials.fromCertificate(serviceAccount))
  .setDatabaseUrl("https://<DATABASE_NAME>.firebaseio.com/")
  .build();

初始化這個選項物件後,即可用它來設定 額外的 Firebase 應用程式執行個體請注意 我們使用 secondary 字串。系統會使用這個名稱來擷取 和其他執行個體加以區別,包括 預設執行個體 (名為 [DEFAULT])。您應該挑選適用於 其他 Firebase 專案的預期用途

下列程式碼片段示範如何連線至其他即時資料庫 (其他 Firebase 功能的 API 採用的模式相同)。

Swift

// Configure an alternative FIRApp.
FirebaseApp.configure(name: "secondary", options: secondaryOptions)

// Retrieve a previous created named app.
guard let secondary = FirebaseApp.app(name: "secondary")
  else { assert(false, "Could not retrieve secondary app") }


// Retrieve a Real Time Database client configured against a specific app.
let secondaryDb = Database.database(app: secondary)

Kotlin+KTX

// Initialize secondary FirebaseApp.
Firebase.initialize(context = this, options, "secondary")

// Retrieve secondary FirebaseApp.
val secondary = Firebase.app("secondary")
// Get the database for the other app.
val secondaryDatabase = Firebase.database(secondary)

Java

// Initialize with secondary app
FirebaseApp.initializeApp(this /* Context */, options, "secondary");

// Retrieve secondary FirebaseApp
FirebaseApp secondary = FirebaseApp.getInstance("secondary");

Web

// Initialize another app with a different config
const secondaryApp = firebase.initializeApp(secondaryAppConfig, "secondary");
// Access services, such as the Realtime Database
// secondaryApp.database();

C++

firebase::App* secondary_app = firebase::App::Create(secondary_app_options, "Secondary");
firebase::database::Database* secondary_database = firebase::database::Database::GetInstance(secondary_app);

Unity

var secondaryApp = Firebase.FirebaseApp.Create(secondaryAppOptions, "Secondary"));
var secondaryDatabase = Firebase.Database.FirebaseDatabase.getInstance(secondaryApp);

Node.js

// Initialize another app with a different config
const secondary = initializeApp(secondaryAppConfig, 'secondary');
// Access services, such as the Realtime Database
// const secondaryDatabase = secondary.database();

Java

// Initialize another app with a different config
FirebaseApp secondaryApp = FirebaseApp.initializeApp(secondaryAppConfig, "secondary");

// Retrieve the database.
FirebaseDatabase secondaryDatabase = FirebaseDatabase.getInstance(secondaryApp);

確保 Analytics 報表

Google Analytics 會在應用程式啟動流程的早期階段收集事件, 可能在設定主要 Firebase 應用程式執行個體前於 在這些情況下,Firebase 參照了 Android 資源 在 Apple 平台上GoogleService-Info.plist,以便查詢正確的 Google 應用程式 用於儲存事件的 ID。因此,建議您使用預設值 設定方法

如果必須設定執行階段設定,請注意下列事項:

  1. 如果您使用 AdMob 並依照建議在啟動時請求廣告, 沒有使用資源時,缺少與行動廣告相關的 Analytics 資料 雲端式設定方法
  2. 請勿在應用程式發行的每個變化版本中提供單一 Google 應用程式 ID。 舉例來說,如果您在GOOGLE_APP_ID 但設定後上傳版本 2 不同的 ID, Analytics 資料遭到捨棄
  3. 在 Apple 平台上,如有下列情況,請勿將 GoogleService-Info.plist 加入專案 您需要在執行階段提供不同的設定 GOOGLE_APP_ID的明顯變化,導致 Analytics 遺失。