Firebase checking for null value (Swift)
Take advantage of the exists() method to determine if the snapshot contains a value. To use your example:
let uid = ref.authData.uid
ref.queryOrderedByChild("uid").queryEqualToValue(uid)
.observeSingleEventOfType(.Value, withBlock: { snapshot in
guard snapshot.exists() else{
print("User doesn't exist")
return
}
print("User \(snapshot.value) exists")
})
.
Here's another handy example, Swift4
let path = "userInfo/" + id + "/followers/" + rowId
let ref = Database.database().reference(withPath: path)
ref.observe(.value) { (snapshot) in
let following: Bool = snapshot.exists()
icon = yesWeAreFollowing ? "tick" : "cross"
}
Checking if Firebase snapshot is equal to nil in Swift
There are a few things going on here, but the most important one is that you cannot test for the existence of children with .ChildAdded
. That makes sense if you think about it: the .ChildAdded
event is raised when a child is added to the location. If no child is added, the event won't be raised.
So if you want to test if a child exists at a location, you need to use .Value
. Once you do that, there are various way to detect existence. Here's one:
ref.queryOrderedByChild("waiting").queryEqualToValue("1")
.observeEventType(.Value, withBlock: { snapshot in
print(snapshot.value)
if !snapshot.exists() {
print("test2")
}
});
Swift 3 getting nil value in firebase while retrieving data
Reload your table view after appending the data to array:
func retriveData() {
ref.observe(.childAdded, with: { (snapshot) in
if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
for snap in snapshot {
if let userDict = snap.value as? Dictionary<String,AnyObject> {
print("user dict - \(String(describing: userDict["name"]))")
let username = userDict["name"] as? String
self.uname.append(username!)
}
}
tableView.reloadData()
}
})
}
Firebase for SWIFT iOS: returning nil value in function
You need to use closures as getDocument()
does not return synchronously.
func display(userid: String, handler: (String) -> Void) {
let docRef = db.collection("user").document(uid)
docRef.getDocument { (document, error) in
if let document = document, document.exists {
if let displayName = document.get("username") as? String {
handler(displayName)
}
} else {
print("Document does not exist")
}
}
}
And use it like so:
self.myLabel.text = "Loading..."
display(userid: {USER_ID}) { [weak self] displayName in
print(displayName)
self.myLabel.text = displayName
}
how to check if Database is empty swift 3 - Firebase
For that you need to check snapshot children count first, whether it's empty or not.
For that -
var ref = Firebase(url: FIREBASE_URL)
ref.observeEventType(.Value, withBlock: { (snapshot: FDataSnapshot!) in
if(snapshot.childrenCount > 0){ // It has value already
}
else{ // Still Empty
// Upload values to firebase
}
})
Hope it will help you to achieve what you want. :)
Firebase on Swift, how to get notified if a query is empty?
you can check if the snapshot exist, this will return a Bool
snapshot.exists()
swift firestore cannot check if documents value nil is
I would say that you would better like to make a safe check, alltogether with casting the type like so:
if let decisions = document.get("decisions") as? [String: String] {
object.decisions = decisions
}
Firebase Snapshot equal to null when value exists
There may be other issues with the code but I would suggest a different approach. Instead of a tight loop to read in the reviews about each post, just include the post_id in each review and then a simple query to read them in.
Posts
"post_id_0" : { //childByAutoId()
"endTime" : "05:32 PM 27/07/2018",
"imageUrl" : "",
"live" : true,
"locationName" : "",
"postTitle" : "hahahahaha ",
"reviews" : {
"review_id_0" : true,
"review_id_1" : true
},
"startTime" : "04:32 PM 27/07/2018",
"views" : 0
ReviewPost
"review_id_0" : { //childByAutoId()
"post_id": "post_id_0", //a reference to the post
"addPostID" : "-LIQ_Aa8s1H067wFeCdR",
"rating" : 5,
"reviewComment" : "Dumplings were rubbish.",
"time" : "2018-08-28 04:58:18 +0000",
"userID" : "LUtRmkAefPNsRjPni5Dn0KAvKBx1"
},
then to get all of the reviews for post_id_0
let reviewPostRef = self.ref.child("ReviewPost")
let query = reviewPostRef.queryOrdered(byChild: "post_id").queryEqual(toValue: "post_id_0")
query.observeSingleEvent(of: .value, with: { snapshot in
for child in snapshot.children {
let childSnap = child as! DataSnapshot
let dict = childSnap.value as! [String: Any]
let comment = dict["reviewComment"] as! String
print(comment)
}
})
and the output is
Dumplings were rubbish.
Related Topics
Create Alert Function in All View Controllers - Swift
Displaying Instances of View Controllers Within Xcode Without Disturbing the Current Hierarchy
Clipping Sound with Opus on Android, Sent from iOS
Live Render Iboutlet Connected Subviews via Ibinspectable Properties
Creating a Rtsp Client for Live Audio and Video Broadcasting in Objective C
Allow Users to Send Messages to Multiple Users Simultaneously in a Messaging App
Completely Unrelated Error Using Coredata
Avaudioplayer Working on Simulator But Not on Real Device
Firebase: Provided Bucket Does Not Match the Storage Bucket of the Current Instance in Swift
Dynamically Passing Closure with Keypaths to a Sorting Function
Array Element Checking in Swift
App Installation Failed: Unknown Error Xcode 7
iOS 3Des with Ecb Return Half Correct Data
Dyld: Library Not Loaded: @Rpath/Mydsk.Framework/Mydsk -> Swift iOS 8.0