配置多個項目

本頁介紹如何在您的應用程式中使用多個 Firebase 專案。

許多應用程式只需要一個 Firebase 專案和入門指南中所述的預設設定。使用多個 Firebase 專案的有用範例包括:

  • 設定您的開發環境以根據建置類型或目標使用不同的 Firebase 專案。
  • 存取應用程式中多個 Firebase 專案的內容。

支援不同環境

一個常見的用例是為您的開發和生產環境支援單獨的 Firebase 專案。

Web 和管理 SDK 是透過直接將值傳遞給其初始化函數來配置的。對於這些 SDK,您可以使用執行時間檢查來選擇開發或生產配置變數。

Android 和 Apple 平台(及其 Unity 和 C++ 包裝器)通常會從設定檔載入設定:Apple 平台上的GoogleService-Info.plist和 Android 上的google-services.json 。這些檔案被讀入由 Firebase 應用程式物件( FIROptionFirebaseOptions )所引用的選項物件( 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檔案由 Google Services gradle 外掛程式處理為 Android 字串資源。您可以在處理 JSON 檔案的 Google 服務外掛程式文件中查看已建立了哪些資源。

google-services.json檔案放置在應用程式模組根目錄下為每個變體命名的專用目錄中,您可以為不同的建置變體擁有多個 google google-services.json檔案。例如,如果您有「開發」和「發布」建置風格,您的配置可以這樣組織:

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

要了解更多信息,請參閱有關添加 JSON 文件的Google 服務插件文件。

然後,這些資源由FirebaseInitProvider加載,該資源在應用程式程式碼之前運行並使用這些值初始化 Firebase API。

由於此提供者只是讀取已知名稱的資源,因此另一個選項是將字串資源直接添加到您的應用程式中,而不是使用 Google Services gradle 插件。您可以透過以下方式執行此操作:

  • 從根build.gradle移除google-services插件
  • 從專案中移除google-services.json
  • 直接添加字串資源
  • 從應用程式build.gradle移除apply plugin: 'com.google.gms.google-services'

在您的應用程式中使用多個項目

有時您需要使用相同的 API 存取不同的項目 - 例如,存取多個資料庫實例。在大多數情況下,有一個中央 Firebase 應用程式物件來管理所有 Firebase API 的配置。該物件作為正常設定的一部分進行初始化。但是,當您想要從單一應用程式存取多個專案時,您將需要一個不同的 Firebase 應用程式物件來單獨引用每個項目。由您來初始化這些其他實例。

在這兩種情況下,您都需要先建立一個 Firebase 選項物件來儲存 Firebase 應用程式的設定資料。有關選項的完整文件可以在以下類別的 API 參考文件中找到:

以下範例顯示如何使用這些類別來支援應用程式中的多個項目:

迅速

// 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();

網路

// 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>");

統一

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

爪哇

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 遵循相同的模式)。

迅速

// 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");

網路

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

統一

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

爪哇

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

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

確保可靠的分析報告

Google Analytics 在應用程式啟動流程的早期收集事件,有時甚至在配置主 Firebase 應用程式實例之前收集事件。在這些情況下,Firebase 會引用 Android 資源或 Apple 平台上的GoogleService-Info.plist來尋找正確的 Google 應用程式 ID 來儲存事件。因此,我們建議盡可能使用預設配置方法。

如果需要運行時配置,請注意以下注意事項:

  1. 如果您使用 AdMob 並按照建議在啟動時要求廣告,則在不使用基於資源的配置方法時,您可能會錯過一些與行動廣告相關的 Analytics 資料。
  2. 僅在應用程式的每個分散式變體中提供一個 Google 應用程式 ID。例如,如果您在配置中使用特定的GOOGLE_APP_ID發布應用程式的版本 1,然後使用不同的 ID 上傳版本 2,則可能會導致分析資料遺失。
  3. 在 Apple 平台上,如果您在運行時提供不同的配置,請勿將 GoogleService-Info.plist 新增至您的專案中,因為這可能會導致GOOGLE_APP_ID發生明顯變化並導致分析遺失。