I am new to firebase and trying to write some data to firebase.
My problem is below :
installed pod 'Firebase/Core'
pod 'Firebase/Database' coacopods
and import Firebase in Xcode, also changed realtime database rule both "read" and "write" are true, everything is connected to google firebase, but still can't write data in realtime database? anyone has same problem like me? can anyone help me to fix it?
code
part one(AppDelegate.swift):
import UIKit
import Firebase
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
**FirebaseApp.configure()**
return true
}
part two(ViewController.swift):
import UIKit
import Firebase
import FirebaseDatabase
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
**let ref = Database.database().reference()**
**ref.child("someid/name").setValue("mike")**
}
}
There is no any error message showing in Xcode or firebase.
I suggest you update your GoogleService-Info.plist by downloading from your console again. This solved my problem.
override func viewDidLoad() {
super.viewDidLoad()
let ref = Database.database().reference()
let value = [
"name": "mike"
] as [String: Any]
ref.child("someid/name").setValue(value)
}
Related
Following various tutorials most of which seem to be from a couple years ago, I am trying to connect to Firebase from an IOS app and having trouble with how and where to import the libraries and, in turn, connect to the database.
In my app delegate, I am able to establish a connection--I think---inside the difFinishLaunching method (I say I think because Firebase does not recognize the app in the console but this seems to be a frequent occurrence so I'm ignoring that and just trying to get the app to build in Xcode for now) as follows:
import UIKit
import FirebaseAnalytics
import FirebaseDatabase
import FirebaseCore
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
let myDB = Database.database().reference().child("items")
}
return true
}
That seems okay in that it builds.
When I try to put a reference to the database in a viewcontroller, however, it throws an error on Database:
import UIKit
import FirebaseCore
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let ref = Database.database().reference(withPath: "items") //THIS LINE THROWS ERROR
What do I need to do to create a property for the Database in a view controller?
Edit: Looking at some other answers on SO, it seems I may have to create a singleton reference to the db connection. If so, where would I put this and how would I reference it?
Thanks for any suggestions
First, your AppDelegate should look something like this
import UIKit
import Firebase
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
return true
}
then, in your first viewController like this:
import UIKit
import Firebase
class ViewController: UIViewController {
var db: Firestore!
override func viewDidLoad() {
super.viewDidLoad()
self.db = Firestore.firestore()
//do something with Firestore
var ref: DocumentReference? = nil
ref = db.collection("users").addDocument(data: [
"first": "Ada",
"last": "Lovelace",
"born": 1815
]) { err in
if let err = err {
print("Error adding document: \(err)")
} else {
print("Document added with ID: \(ref!.documentID)")
}
}
}
}
Keep in mind I have set my Firestore rules to allow anyone to read/write, which is dangerous so please start working through the Authentication guide once you get this working.
Note that the above code pretty much came straight from the Getting Started guides Add Firebase To An App and Installation and setup
Based on advice, I would like to manage API keys using Firebase Remote Config to avoid hard-coding API keys like google_maps_flutter suggests. It has an AppDelegate.swift like:
import UIKit
import Flutter
import GoogleMaps
#UIApplicationMain
#objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GMSServices.provideAPIKey("YOUR KEY HERE")
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
How can the above be modified to fetch the API key from Firebase Remote Config and then pass it to GMSServices?
Based on this article, I came up with:
import UIKit
import Firebase
import Flutter
import GoogleMaps
//import os.log
#UIApplicationMain
#objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
FirebaseApp.configure()
RemoteConfig.remoteConfig().fetchAndActivate() { status, error in
let apiKey : String = RemoteConfig.remoteConfig()["Google_Maps_SDK_for_iOS_API_KEY"].stringValue ?? "MISSING";
// os_log("Google_Maps_SDK_for_iOS_API_KEY = '%#'", apiKey)
GMSServices.provideAPIKey(apiKey)
}
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
Is there a better way?
I was thinking of making this as a comment, but decided to make it as my answer as it was too long.
I think it's one way of getting keys from remoteConfig, but again failure can happen where fetch config was not retrieved. One way to solve it is by having a force refresh when it fails, but then again you are relying on firebase for those keys and if for some reason (experienced it before firebase was acquired by google) it went down your app then will be unuseable (so as for many apps).
For me, I still put my API keys bundled with the app just to make sure all the important functionality works.
Another option will be having your API Keys bundled and then having a WebService call to check for new keys once the current keys you have has expired/change. That way you have the capability to immediately expire your keys and change it to another one.
So I made a project that included lots of extra code so I could try out different things, and I am slowly copy-pasting the files from textedit into my new project.
I created a new Firebase account, added the google plist file, initialized and installed the pods needed (also changed the iOS version to 10.0 on the pod file)... yet it's still wanting me to use FirebaseApp.configure() instead of FIRApp.configure().
Should I just delete the whole thing and try again? I just created a new Xcode project, so if I had to delete it right now that would be fine.
import UIKit
import Firebase
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
override init() {
super.init()
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FIRApp.configure()
return true
}
There hasn't been much code written, but I can't figure out what could have made this happen... especially since I just started the new project.
FirebaseApp.configure() is correct. I checked out the documentation just now and FIRApp.configure() has been renamed FirebaseApp.configure(). I also ran pod update on one of my projects just to confirm, and my project had me change to using FirebaseApp.configure(). So no need to rebuild!
I can confirm that FIRApp.configure() can be changed to FirebaseApp.configure()
In firebase it suggest to add the following to app delegate:
"
import UIKit import Firebase
#UIApplicationMain class AppDelegate: UIResponder,
UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?)
-> Bool {
FirebaseApp.configure()
return true } }
"
This includes the FirebaseApp.configure() command
So I am attempting to integrate Google's Firebase into my SpriteKit game and was having a small issue.
The instruction from Firebase is..."Configure a FIRApp shared instance, typically in your application's application:didFinishLaunchingWithOptions: method:FirebaseApp.configure()".
Now I've located the file called AppDelegate.swift in my Xcode project but when I place it into the first function, which matches the named one in the instructions I get the following error Use of unresolved Identifier FirebaseApp.
And I remembered to import Firebase at the top of document. Any suggestions?
It is FIRApp, not FirebaseApp.
FIRApp.configure()
Note: Don't forget to import the Firebase module.
import Firebase
Your app delegate needs to look something like this:
import UIKit
import Firebase
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
FIRApp.configure()
return true
}
}
Make sure you call FIRApp.configure() before the return true and remember to import Firebase.
I'm trying to upgrade my app to the new version of Firebase. I went through the setup guide and edited all of my code to match the new syntax. However, when I run the app, I get these two errors.
The default app has not been configured yet.
Terminating app due to uncaught exception 'MissingDatabaseURL', reason: 'Failed to get FIRDatabase instance: FIRApp object has no databaseURL in its FirebaseOptions object.'
I have FIRApp.configure() in the AppDelegate and I have the GoogleServices-Info.plist imported into my project. The plist has all of the correct info as well. Anyone else running into this or know how to fix it?
Here's the answer to your problem:
To configure Firebase you have to execute FIRApp.configure() somewhere. After this is done you can use let firebaseDatabaseReference = FIRDatabase.database().reference() to get a reference to that database and start using it. The problem isn't with Firebase "per se" but with how Swift behaves.
If you put FIRApp.configure() in your AppDelegate func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool and then in the MyDatabase class you use let firebaseDatabaseReference = FIRDatabase.database().reference() outside of your declared functions sometimes the code FIRDatabase.database().reference() executes before the application didFinishLaunchingWithOptions function is executed.
Essentially your class is trying to get a reference to the Firebase database before it has a chance to configure itself, generating the error in the console "The default app has not been configured yet."
Note: This doesn't happen all the time, sometimes the application is slow to start, in iOS Simulator for example, and it doesn't have a chance to finish before MyDatabase "let" executes and tries to get a reference.
That is why moving the FIRApp.configure() code to override init() in AppDelegate works, essentially it makes sure the configure code gets executed when AppDelegate is initialised (in this and most cases, before MyDatabase is initialised)
override init() {
super.init()
FIRApp.configure()
// not really needed unless you really need it FIRDatabase.database().persistenceEnabled = true
}
Also make sure you super.init() (so you super classes get the "message") so you override doesn't do more harm than good.
I'm also using Fabric and in my case it was the order of Fabric and Firebase initializations. I had to initialize Firebase first.
So changing
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
Fabric.with([Crashlytics.self])
FirebaseApp.configure()
...
}
to:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
Fabric.with([Crashlytics.self])
...
}
fixed the problem.
In AppDelegate.m, outside of didFinishLaunchingWithOptions,
override init() {
FIRApp.configure()
FIRDatabase.database().persistenceEnabled = true
}
Make sure you are having DATABASE_URL key in your GoogleService-Info.plist
Swift 5 - Easy Solution
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
return true
}
//MARK:- This function will auto run and firebase will configure successfully
override init() {
super.init()
FirebaseApp.configure()
// not really needed unless you really need it
FIRDatabase.database().persistenceEnabled = true
}
Happy Coding
iOS 9.2
Swift 2.1.1
Xcode 7.2.1
Mac OSX 10.10.5
Same error here using the following code:
AppDelegate.swift:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
FIRApp.configure()
return true
}
ViewController.swift:
import UIKit
import Firebase
class ViewController: UIViewController {
var db = FIRDatabase.database().reference()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Create some data in Firebase db:
db.child("key").child("subkey").setValue("hello world")
}
I also added the file GoogleService-Info.plist to my project directory as described in the Firebase Getting Started Guide.
And I made my Firebase db public with the following Rules:
{
"rules": {
".read": true,
".write": true
}
}
Making the following changes to ViewController.swift is what worked for me:
class ViewController: UIViewController {
var db: FIRDatabaseReference!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
db = FIRDatabase.database().reference()
db.child("key").child("subkey").setValue("hello world")
}
Prior to running my app, my Firebase db looked like this:
myiosdata-abc123: null
After running my app, my Firebase db looked like this:
myiosdata-abc123
- key
|
+--- subkey: “hello world”
I had several normal working projects with FIRApp.configure () code in AppDelegate.swift:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
FIRApp.configure()
return true
}
Everything worked great for quite some time, but yesterday and today I opened a Swift 3 project inside my Xcode 7.3.1 (I am still working in Swift 2, but opened Swift 3 project to see what is changed), and suddenly in all my Swift 2 apps and projects that I am still working on, got the same error:
The default app has not been configured yet
Every project now when I open in XCode, getting same error, I didn't know what to do, but after implementing #MichaelWilliams' code, everything works fine again.
I have debug my Xcode (clear and reload console), but nothing works beside this new approach by Michael.
This one resolved my problem:
override init() {
FIRApp.configure()
FIRDatabase.database().persistenceEnabled = true
}
Can this new code somehow make my app's unstable and can I be afraid to see problems with connecting/working with Firebase database now?
Try re-download GoogleService-Info.plist from your console and add it to your project, That worked for me!
If you are using Xcode 9, Swift 4 and Firebase 4 please do the following:
override init() {
FirebaseApp.configure()
Database.database().isPersistenceEnabled = true
}
The cleanest solution to me here is to have lazy properties in case you want to have the db on top of your file. So let's say you have a FirebaseService class where you want to have Firestore.firestore() db constant to use it in all of the functions in that class:
private lazy var db = Firestore.firestore()
Or if you are using Firebase Storage:
private lazy var storage = Storage.storage().reference()
Also keep in mind that if you are referencing the Database/Storage in init() of your classes, you still might have the same problem so avoid that.