问题
In Firebase 3.0+ the method to get the database reference was as such:
var ref: FIRDatabaseReference!
ref = FIRDatabase.database().reference()
ref.child("rooms").observeSingleEventOfType(.Value, withBlock: { (snapshot) in
if snapshot.hasChild("room1"){
print("true rooms exist")
}else{
print("false room doesn't exist")
}
})
In Firebase 4.0 the naming convention changed but I can't get it to work!?
var ref: DatabaseReference!
ref = Database.database().reference()
Has anyone else encountered this?
The swift compiler is suggesting removing the () from the lowercase database function call
if you remove it, it then throws the error message:
- Database has no member reference
So how do you get the reference then!?
Pod file:
pod 'Firebase/Core'
pod 'Firebase/Database'
回答1:
The firebase documentation needs to be updated. 1. import both of these at the top of your class
import FirebaseCore
import FirebaseDatabase
- Getting a DB reference only works within ViewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
var ref: DatabaseReference!
ref = Database.database().reference()
}
回答2:
You need to use the update code, perhaps the compiler hasn't done a good job of suggesting a fix
var ref: DatabaseReference!
ref = Database.database().reference()
ref.child("rooms").observeSingleEvent(of: .value, with: { (snapshot) in
// ...
})
as you can see, the code works perfectly, consider pod deintegrate & pod update
回答3:
Your syntax seems right to me (for the new Firebase 4):
var ref: DatabaseReference!
ref = Database.database().reference()
And, looking at their source code (FIRDatabase.h), everything you are doing matches perfectly:
FIR_SWIFT_NAME(Database)
@interface FIRDatabase : NSObject
+ (FIRDatabase *) database FIR_SWIFT_NAME(database());
- (FIRDatabaseReference *) reference;
Are you sure you are on their latest SDK version? As a last resort, try this:
pod cache clean
rm Podfile.lock
rm -rf Pods
pod install
rm -rf DerivedData
回答4:
For Firebase 4.0, there is a change
- Removing the FIR prefix across names for all constants, protocols, classes, enums, and type definitions.
- Renaming FIRApp to FirebaseApp.
- Renaming FIROptions to FirebaseOptions.
Link: https://firebase.google.com/docs/reference/ios/naming-migration-guide
来源:https://stackoverflow.com/questions/44078673/get-a-database-reference-in-the-new-firebase-4-0-release