Используйте более одной базы данных Firebase в одном приложении - Swift
У меня есть база данных firebase, подключенная к моему приложению с помощью GoogleService-Info.plist и т.д. Это отлично работает.
Я также хотел бы подключить мое приложение к второй базе данных firebase.
Похоже, эта проблема была решена для Android здесь.
Любая идея, как добавить вторую базу данных firebase с Swift в Xcode?
EDIT: я пробовал несколько подходов, включая использование FIROptions для создания экземпляра базы данных. Я просто не могу правильно структурировать код. Любая помощь приветствуется!
Ответы
Ответ 1
Правильный способ инициализации другой базы данных - инициализировать другое приложение, используя конструктор FIROptions
, например:
FIRDatabase().database() // gets you the default database
let options = FIROptions(googleAppID: bundleID: , GCMSenderID: , APIKey: , clientID: , trackingID: , androidClientID: , databaseURL: "https://othernamespace.firebaseio.com", storageBucket: , deepLinkURLScheme: ) // fill in all the other fields
FIRApp.configureWithName("anotherClient", options: options)
let app = FIRApp(named: "anotherClient")
FIRDatabase.database(app: app!) // gets you the named other database
Или вы можете инициализировать из другого названного plist, а не из огромного конструктора:
let filePath = NSBundle.mainBundle().pathForResource("MyCool-GoogleService-Info", ofType:"plist")
let options = FIROptions(contentsOfFile:filePath)
Ответ 2
С новейшей версией Firebase вы должны сделать:
let filePath = Bundle.main.path(forResource: "My-GoogleService", ofType: "plist")
guard let fileopts = FirebaseOptions.init(contentsOfFile: filePath!)
else { assert(false, "Couldn't load config file") }
FirebaseApp.configure(options: fileopts)
Ответ 3
Я пытаюсь инициализировать несколько проектов Firebase в моем приложении, но приложение получает уведомление только для первой конфигурации.
Это мой код.
//Configure first service firebase
let filePath1 = Bundle.main.path(forResource: "GoogleService-Info", ofType: "plist")
guard let fileopts1 = FirebaseOptions(contentsOfFile: filePath1!)
else { assert(false, "Couldn't load config file") }
FirebaseApp.configure(name: "first", options: fileopts1)
//Configure second service firebase
let filePath = Bundle.main.path(forResource: "GoogleService-Cuarto", ofType: "plist")
guard let fileopts = FirebaseOptions(contentsOfFile: filePath!)
else { assert(false, "Couldn't load config file") }
FirebaseApp.configure(options: fileopts)
Messaging.messaging().delegate = self
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
Но Firebase мой проект в Firebase не обнаружил мое приложение.
Помоги мне!!!