首页 > 解决方案 > 使用 swift4 在 xcode 中为单个项目使用不同的 GoogleService-Info.plist

问题描述

我有一个项目,但有 4 个不同的环境(Dev、Staging、QA、Production)。我已经从移动设备的设置中给出了他们的(环境的 web 服务 url)路径。现在我想为所有这些不同的环境使用不同的 GoogleService-info.plist。就像我从后端选择 Dev 时,项目应该只使用 Dev 项目的 GoogleService-Info.plist。这些 GoogleService-Info.plist 是在 4 个不同的帐户上创建的。项目应该以编程方式采用 GoogleService-info.plist 的路径。我试过下面的代码

1] 通过参考这个url,我创建了两个文件夹 Dev 和 QA(现在),并尝试通过编程方式给出它们的路径

#if DEV
    print("[FIREBASE] Development mode.")
    filePath = Bundle.main.path(forResource: "GoogleService-Info", 
ofType: "plist", inDirectory: "Dev")
    #elseif QA
    print("[FIREBASE] QA mode.")
    filePath = Bundle.main.path(forResource: "GoogleService-Info", 
ofType: "plist", inDirectory: "QA")
    #endif
    let options = FirebaseOptions.init(contentsOfFile: filePath)!
    FirebaseApp.configure(options: options)

但它会引发错误

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

 let options = FirebaseOptions.init(contentsOfFile: filePath)!

这条线

2] 其次,我通过 GoogleService-Info-QA.plist 更改了 GoogleService-Info.plist 的名称,并尝试以编程方式访问此文件

private func configureFirebase() {
    guard   let plistPath = Bundle.main.path(forResource: 
"GoogleService-Info-QA", ofType: "plist"),
        let options =  FirebaseOptions(contentsOfFile: plistPath)
        else { return }
    FirebaseApp.configure(options: options)
}

但它会引发错误

Terminating app due to uncaught exception 'FIRAppNotConfigured', 
reason: 'Failed to get default Firebase Database instance. Must 
call `[FIRApp configure]` (`FirebaseApp.configure()` in Swift) 
before using Firebase Database.

标签: swiftfirebasefirebase-realtime-databasemacros

解决方案


将此代码片段放在应用程序didFinishLaunchingWithOptions委托函数中的 AppDelegate.swift 中,在return true

//Configure Firebase based on the app's environment
#if DEV
   guard let filePath = Bundle.main.path(forResource: "GoogleService-Info-DEV", ofType: "plist") else { return }
   let options = FIROptions(contentsOfFile: filePath)
   FIRApp.configure(with: options!)
#elseif QA
   guard let filePath = Bundle.main.path(forResource: "GoogleService-Info-QA", ofType: "plist")  else { return }
   let options = FIROptions(contentsOfFile: filePath)
   FIRApp.configure(with: options!)
#endif

您需要确保您的 plist 文件被相应地命名,并确保它们是您的目标的一部分:

  • 选择 GoogleService-Info-DEV 文件并在右侧的 FileInspector 中确保为您的应用目标选中复选框。对 GoogleService-Info-QA 文件执行相同操作。

您的文件应放置在主文件夹中,就像放置普通的 Google-Info.plist 文件一样。


推荐阅读