How can i fetch specific data from firebase and store it in a dictionary? - swift

I'm trying to fetch data from my firebase database, such that i can store it in a form of dictionary which is a type [String: [Any]] where key is the unique id and the value is a type of array which has the data stored under uniqueID->Question.
func getData(currUser: String, completion: #escaping (([String : [Any]]) -> ())) {
var newArray = [String : [Any]]()
let ref = Database.database().reference(fromURL: "MYURL").child("users/\(currUser)/Questions").observeSingleEvent(of: .value, with: { (snap) in
let enumerator = snap.children
while let rest = enumerator.nextObject() as? DataSnapshot, let value = rest.value{
newArray.updateValue([value], forKey: rest.key)
}
completion(newArray)
})
}
this completion block gives me:
["-LlpbizBpQTXOQ6zv0zd": [{
Qusetion = (
Hello,
test,
kkkkkkkkkkk
);
}]]]
Instead how can i get
["-LlpbizBpQTXOQ6zv0zd": [Hello,test,kkkkkkkkkkk]]

You're converting the value to a string, while it's actually a JSON object. That's why the value in your dictionary is a JSON object.
To only get the question text under Qusetion (typo?), you'll need to loop over that child snapshot and collect the individual values. Something like:
var newArray = [String : [Any]]()
let ref = Database.database().reference(fromURL: "MYURL").child("users/\(currUser)/Questions").observeSingleEvent(of: .value, with: { (snap) in
let enumerator = snap.children
while let rest = enumerator.nextObject() as? DataSnapshot {
var values = [String]
let valueEnumerator = rest.childSnapshot(atPath: "Qusetion").children
while let valueRest = valueEnumerator.nextObject() as? DataSnapshot, let value = rest.value {
values.append(value)
}
newArray.updateValue([values], forKey: rest.key)
}
completion(newArray)
})

Related

Not able to read data from Firebase realtime database

I have stored the comments under a post in firebase realtime database. The problem i have is that when i try to parse out the data from firebase i get an error that says Unexpectedly found nil while unwrapping an Optional value. So for example if i try to pront the data stored under degree, i get this nil error. But when i print "comments" instead of the "degree" i successfully fetch the data. My database structure looks like this.
func obeserveComments() {
// get auto-id of post
let commentKey = self.keyFound
let postRef = Database.database().reference().child("posts").child(commentKey)
var tempComments = [Comments]()
postRef.observe(.value, with: {(snapshot) in
if let dict = snapshot.value as? [String:Any] {
if let comments = dict["comments"] as? [String:Any] {
let degree = comments["reply degree"] as! String
// let name = comments["reply name"] as! String
// let text = comments["reply text"] as! String
// let university = comments["reply university"] as! String
// let photoURL = comments["reply url"] as! String
// let url = URL(string: photoURL)
// let timestamp = comments["timestamp"] as! Double
print(degree)
}
}
})
}
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)")
}
})
}
Its because firebase is returning your data like this
{
"MAKFW244kdL)Cw;1": [Array of data],
"LOPSw!35pa3flAL4": [Array of data],
"ALV34VR4_A6Vn1a": [Array of data]
}
So change your initial casting of snapshot.value to this:
if let dict = snapshot.value as? [String: [String: Any]]
then loop through that new dictionary like this:
for objectJson in dict.values {
if let comments = objectJson["comments"] as? [String: [String: Any]] {
for commentJson in comments.values {
let degree = commentJson["reply_degree"] as? String
}
}
}
Update
Just read through your post again and noticed your trying to access the comments directly with a key, your first going to need to provide the PostId. Then you can use the above code to loop through the objects
let postRef = Database.database().reference().child("posts").child(postID)
alternatively I believe you can have the comments returned as a normal list by doing something like this:
let postRef = Database.database().reference().child("posts").child("\(postID)/{id}")

Firebase Snapshot Isn't showing Data

Basically everything is working, except the showChild func is returning completion([]) because of the guard catData = Category(snapshot: catInfo). I am wondering why the guard let is returning completion. When I debug, catInfo does have 1 value as shown in my pic of database and I want to append catData.main to "cats". Below is code for the service method and Category model as well.
Firebase Database
static func showChild(completion: #escaping ([String]) -> Void) {
let ref = Database.database().reference().child("category").child(User.current.uid)
ref.observeSingleEvent(of: .value, with: { (snapshot) in
guard let snapshot = snapshot.children.allObjects as? [DataSnapshot] else {
return completion([])
}
var cats = [String]()
for catInfo in snapshot {
guard let catData = Category(snapshot: catInfo) else {
return completion([])
}
cats += catData.main
}
completion(cats)
})
}
import Foundation
import FirebaseDatabase.FIRDataSnapshot
class Category {
var key: String?
let main: [String]
init?(snapshot: DataSnapshot) {
guard !snapshot.key.isEmpty else {return nil}
if let dict = snapshot.value as? [String : Any]{
let main = dict["main"] as? [String]
self.key = snapshot.key
self.main = main ?? [""]
}
else{
return nil
}
}
}
The issue is pretty straightforward.
While your snapshot contains at least one node of data, it's not in a format that the Category init method understands. You're iterating over it's child nodes and in your screenshot, there's only one, with a key of 'main'
You are observing this node
fb_root
category
2ayHe...
and then you're iterating over it's child nodes which will be
main
0: Performance
so the key is 'main' and it's value is '0: Performance'
but your Category class is looking for a child node of 'main'
let main = dict["main"] as? [String]
There's not enough info to understand what will be contained in the rest of the structure so I can't tell you how to correct it, but at least you know what the problem is.
To clarify, this line
if let dict = snapshot.value as? [String : Any]
will make dict = [0: "Performance]

I am trying to query a firebase database in while the user is typing, but I keep getting this error

So I found this code to query your database while the user is still typing, but the code was outdated and I've been updating it, but there's an error that I don't know how to fix.
func findFriends(text: String) -> Void {
let ref = Database.database().reference()
ref.child("users").queryOrdered(byChild: "username").queryStarting(atValue: text).queryEnding(atValue: text+"\u{f8ff}").observe(.value, with: { snapshot in
let user = User()
let userArray = [User]()
for u in snapshot.children{
user.name = u.value!["name"] as? String
}
})
I get an error in the last line and it says:
Value of type 'Any' has no member 'value'
The elements in snapshot.children are of type Any, which doesn't have a value property. To get at the value property you need to cast u to a DataSnapshot:
for userSnapshot in snapshot.children{
let userSnapshot = userSnapshot as! DataSnapshot
guard let dictionary = userSnapshot.value as? [String: Any] else { return }
user.name = dictionary["name"] as? String
}
Alternatively, you put the cast in the loop:
for userSnapshot in in snapshot.children.allObjects as? [DataSnapshot] ?? [] {
guard let dictionary = userSnapshot.value as? [String: Any] else { return }
user.name = dictionary["name"] as? String
}

How do I get specific values from children in firebase using Swift 4?

My Firebase Database
More specifically, I have randomly generated children(Listings) and from those randomly generated Listings I would like to get the string value from the keys.
For example, if I wanted the Photo URL address, I would like to get the string value of the key "PhotoURL:".
Thank you in advance !
First you need to do is to import Firebase and then call a function from the Database class like so:
let ref = Database.database().reference().child("Listings")
You can call child recursively to go deeper into your tree
//.child("Listings").child("SomeListing").child("PhotoURL")
Then call observeSingleEvent to receive the values from firebase.
Your value is stored in the snapshot variable
ref.observeSingleEvent(of: .value, with: { (snapshot) in
guard let listingsDictionary = snapshot.value as? [String: Any] else { return }
listngsDictionary.forEach({ (key, value) in
// Here you can iterate through it
})
}) { (err) in
print("Failed to fetch following listings:", err)
}
Here is the code to get child values from Listings. 
var ListArr = [ListModel]()
let ref = Database.database().reference().child("Listings")
ref.observe(.childAdded, with: { (snapshot) in
print(snapshot)
guard let dictionary = snapshot.value as? [String : AnyObject] else {
return
}
let Obj = ListModel()
Obj.UID = snapshot.key
Obj.PhotoURL = dictionary["PhotoURL"] as? String
self.ListArr.append(Obj)
}, withCancel: nil)
}
You can set up the model class
class ListModel: NSObject {
var UID:String?
var PhotoURL:String?
}

facing Issue in parsing in swift3

I am trying to parse the emergency data in into emergency struct but it never statifies the condition and get into else case.Here is my code and structure.Some thing i have written woring in first line.
if let emergencyDict = snapshotValue["emergency"] as? [String:[String:Any]]{
for (emerId, emerData) in emergencyDict {
let emer = Emergency.init(emergency: emerData as NSDictionary)
emergency.append(emer)
}
}
else{
let emer = Emergency.init(emerg: "" as AnyObject)
emergency.append(emer)
}
struct Emergency{
var emer_id: String
var emer_name: String
var emer_phoneNo: String
init(emergency: NSDictionary) {
if emergency.object(forKey: "id") != nil {
emer_id = emergency.object(forKey: "id") as! String
}
else{
emer_id = ""
}
}
}
The problem you are having emergency as Array with type [Any] and if you remove the first object then you get Array of type [[String:Any]]. So try like this way.
if let array = snapshotValue["emergency"] as? [Any],
let emergencyArrar = Array(array.dropFirst()) as? [[String:Any]] {
print(emergencyArray)
for emergency in emergencyArray {
print(emergency)
}
}
You have written wrong in this line:
if let emergencyDict = snapshotValue["emergency"] as? [String:[String:Any]]{
It should be:
if let emergencyDict = snapshotValue["emergency"] as? [[String:Any]]{
This question should belong to query from firebase database.
// you have to get the children in emergency,
// then get the value(dictionary) of each child
ref.child("emergency").observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let keys = value?.allKeys // [1, 2, 3 ....]
for key in keys {
ref.child("emergency").child(key)..observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
// Here is your dictionary
}
}
}) { (error) in
print(error.localizedDescription)
}