swift - 使用 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.
解决方案
将此代码片段放在应用程序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 文件一样。
推荐阅读
- apache-spark - 如果在数据加载后执行期间删除了源数据,如何保留在 pyspark 中加载的转换后的数据帧?
- python - python tkinter 分别读取用户输入文本标签每个字母
- ios - 使用 fastlane match 给我:您的开发者帐户需要更新
- javascript - 如何检测何时释放所有键
- python - 如何加载我自己的数据(不是基于图像的)而不是 mnist 数据
- javascript - 如何在 ngfor 完成 agnular 11 后销毁 owl carousel 然后重新初始化它?
- powershell - 将个人服务计划分配给 0365 用户
- html - XPath 文本/替换以查找可能包含软连字符的文本
- c# - 如何使用 MongoDB C# 将新对象插入(推送)到嵌套数组中?
- java - 简单的数据库编辑器