Issues Reading Data from Firebase Database

Not able to read data from Firebase realtime database

The answer by @aytroncb is a good answer, I prefer to leave Firebase data 'Firebasy' as long as possible. In other words coverting to dictionaries looses ordering and and find code like this

[String: [String: [String: Any]]] 

To be very hard to read.

I prefer

let snap = snapshot.childSnapshot("comments") //snap becomes a DataSnapshot

So my solution maintains the order and leverages .childSnapshot to leave data in it's DataSnapshot form.

func readPostComments() {
let postRef = self.ref.child("posts") //self.ref points to my firebase
postRef.observeSingleEvent(of: .value, with: { snapshot in
let allPosts = snapshot.children.allObjects as! [DataSnapshot]
for postSnap in allPosts {
print("postId: \(postSnap.key)")
let commentsSnap = postSnap.childSnapshot(forPath: "comments") //will be a DataSnapshot
let allComments = commentsSnap.children.allObjects as! [DataSnapshot]
for commentSnap in allComments {
print(" commentId: \(commentSnap.key)")
let replyDegree = commentSnap.childSnapshot(forPath: "reply_degree").value as? String ?? "No Degree"
let replyName = commentSnap.childSnapshot(forPath: "reply_name").value as? String ?? "No Name"
print(" degree: \(replyDegree) by: \(replyName)")
}
}
})
}

EDIT

For a single post, remove the top part of the code that reads in and iterates over all posts.

func readCommentsForOnePost() {
let postRef = self.ref.child("posts")
let postCommentRef = postRef.child("post_0")
postCommentRef.observeSingleEvent(of: .value, with: { snapshot in
print("postId: \(snapshot.key)")
let commentsSnap = snapshot.childSnapshot(forPath: "comments") //will be a DataSnapshot
let allComments = commentsSnap.children.allObjects as! [DataSnapshot]
for commentSnap in allComments {
print(" commentId: \(commentSnap.key)")
let replyDegree = commentSnap.childSnapshot(forPath: "reply_degree").value as? String ?? "No Degree"
let replyName = commentSnap.childSnapshot(forPath: "reply_name").value as? String ?? "No Name"
print(" degree: \(replyDegree) by: \(replyName)")
}
})
}

Issues reading data from Firebase Database

The data is correctly added to the array, just not at the time that you print the array's contents.

If you change the code like this, you can see this:

let commuteBuilder = Commutes()

Database.database().reference().child("Users").child(user).child("Trips").observe(DataEventType.childAdded, with: { (snapshot) in

if let dict = snapshot.value as? NSDictionary {
commuteBuilder.distance = dict["Distance"] as! Double
commuteBuilder.title = dict["TripName"] as! String
commuteBuilder.transportType = (dict["Transport"] as? String)!

}

commuteArray.append(commuteBuilder)
print("added one, now have \(commuteArray.count)")
})
print("returning \(commuteArray.count)")
return commuteArray

You'll see it print something like this:

returning 0

added one, now have 1

added one, now have 2

etc.

This is likely not the output you expected. But it is working as intended. Firebase loads data from its database asynchronously. Instead of blocking your code, it lets the thread continue (so the user can continue using the app) and instead calls back to the code block you passed to observe when new data is available.

This means that by the time this code returns the array it is still empty, but it later adds items as they come in. This means that you cannot return data from a function in the way you are trying.

I find it easiest to change my way of thinking about code. Instead of "First get the data, then print it", I frame it as "Start getting the data. When data comes back, print it".

In the code above, I did this by moving the code that prints the count into the callback block. Instead of doing this, you can also create your own callback, which is called a completion handler or closure in Swift. You can find examples in this article, this article, this question Callback function syntax in Swift or of course in Apple's documentation.

Firebase Realtime Database reading data doesn't work

I've found my issue. The problem is getting access to the database. I had my rules like so:

{
"rules": {
".read": "auth.uid != null",
".write": "auth.uid != null"
}
}

Which was the correct setup if you were an authenticated user. I read up on Firebase Permission Denied
even though I didn't get an error in the console. I set the JSON to true like so:

{
"rules": {
".read": true,
".write": true
}
}

and that solved my problem.

It's really unfortunate that this silly mistake caused all this fuss. If we can't access the database, we should get an error in the console. I know that the listener on('value') will only return if there is a value there, but there should be a more practical listener that will let you know if you don't have access to the database. Especially for beginners like me, it's hard to keep track of everything else that's going on-that little things like this hang us up for no good reason.

Firebase Realtime Database retrieving data issue

Seeing your code I can say that contains no error. To solve the problem, just comment the following line of code:

database.setPersistenceEnabled(true);
ref.keepSynced(true);

And your problem will be solved. Your data will be displayed for the fist time.

KOTLIN/FIREBASE Error when I try get data from firebase database - Client is offline

Ok, problem was with Firebase not my application. I don't know why but when I started app in every try Firebase closed my connection with database. I tried add to google.services.json some links to database and change some settings but this didn't work. After all I removed app from firebase and delete file google.services.json. I added app again on website then I connect app with firebase and new google.services.json was set. That's all everything is working thanks for help.



Related Topics



Leave a reply



Submit