Query Firebase for selected values in iOS Swift - ios

I am creating a chat app in Swift where I am using Firebase. In my Firebase database, I have an object called members. From that members, I only want data which has a particular key name.
My structure:
So from members, I only want data which has anuj as the key.
Code:
refMembers.queryOrderedByKey().queryEqual(toValue: true, childKey: "anuj").observe(.value, with: { (snap) in
Logger.sharedInstance.log(whatToPrint: snap.childrenCount as AnyObject)
*******This crashes my app*******
})
Code
refMembers.queryOrderedByValue().queryEqual(toValue: true).observe(.value, with: { (snap) in
Logger.sharedInstance.log(whatToPrint: snap.childrenCount as AnyObject)
******* here i get no data*******
})

Let's try:
refMembers.orderByChild("anuj").equalTo(true).on("value", function(snapshot) {
console.log(snapshot.key)
})
Read more Firebase Docs

Related

Query Firebase Database With Swift

I am trying to query an entry in my firebase realtime database with Swift to basically see if an entry exists with the owner = 33206. My current code is not returning what I need, how can I fix this query?
Here is my code:
var promoCodes: DatabaseReference {
return ref.child("PromoCodes")
}
func getIsAffiliate() {
promoCodes.child("owner").queryEqual(toValue: 33206).observeSingleEvent(of: .value) { snapshot in
print("SNAP HERE: \(snapshot)")
AffiliateService.isAffiliate = snapshot == nil
}
}
Output: SNAP HERE: Snap (owner) <null>
The snapshot passed to your code will never be nil. To check if there are matching nodes, you can check snapshot.exists() instead.

App crashing while trying to store data on Firestore

App Crashing with error:
FIRESTORE INTERNAL ASSERTION FAILED: Invalid document reference. Document references must have an even number of segments, but users_table has 1
I am trying to store like this:-
func updateFirestorePushTokenIfNeeded() {
if let token = Messaging.messaging().fcmToken {
let usersRef = Firestore.firestore().collection("users_table").document(userID)
usersRef.setData(["fcmToken": token], merge: true)
}
}
My firestore is empty right now.
That error message almost certainly means that userID is nil or empty. You should verify that you're passing the correct values to Firestore.

Update a particular subchild in firebase realtime database swift 4

The screenshot above is of the database i created. I successfully am able to upload and retreive data through code but i dont know how to update a subchild. For instance if i want to update the subchild user_name how can i acheive this in swift any snippet would be appreciated.
ref.child("USERS").child(email).child("user_name").setValue("new user name"){
(error:Error?, ref:DatabaseReference) in
if let error = error {
//error
} else {
//do stuff
}
}
}
It's simple, you need just call setValue on the child like this:
ref.observeSingleEvent(of: .value, with: { (snapshot) in
self.ref.child("USERS").child(email).child("user_name").setValue("new User Name")
})

Output order becomes different in nested query, using Firebase 3, Swift

I'm using Firebase to store user info, and I have this nested function that fetch the post info, and then using the UID in post to fetch the user info.
Nested function to fetch post info and then fetch user
func fetchUser(completion: #escaping (User) -> Void) {
REF_POST.queryOrdered(byChild: "timestamp").observe(.childAdded, with: { (postData) in
let post = ConvertPost(data: postData.key)
print(post.uid) >>>>>>UID ordered by timestamp<<<<<<<<
REF_USER.child(post.uid).observeSingleEvent(of: .value, with: { (userData) in
print(post.uid) >>>>>>UID order becomes different<<<<<<<<
let user = ConvertUser(data: userData)
completion(user)
})
}
I have a print(uid) before observing the users, the output is ordered by timestamp, which is what I want:
PXT6********
WT7i********
WT7i********
PXT6********
And a print(uid) inside observing users, the output order is different:
WT7i********
WT7i********
PXT6********
PXT6********
so my question is why the order becomes different?
I'm calling the method in ViewDidLoad()
Is it something to do with the closure block?
Question Update
After some testing, I found that the output will always group the same uid together, something like A,A,B,B,C,C. Please help me.
Use this code below:
func observeUsers(uid: String, completion: #escaping (User) -> Void) {
print(uid)
REF_USERS.keepSynced(true) // <-- this will make sure your code will update with fresh data
REF_USERS.child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
print(uid)
let user = ConvertUser(data: snapshot.value)
completion(user)
}
})
}
Either use that code, or disable data persistance in your appDelegate. More information:Firebase : What is the difference between setPersistenceEnabled and keepSynced? and in the docs of Firebase ofcourse.

Retrieving data with .Value and .ChildAdded

I have a list of data to retrieve from Firebase, using Swift.
I tried to get the data using .Value and Firebase returns a dictionary with the IDs of each item and for each ID the info associated.
The endpoint I am calling is /ideas.
let ideasRef = firebase.childByAppendingPath(IdeaStructure.PATH_IDEAS)
ideasRef.observeEventOfType(.Value, withBlock: { snapshot in
print(snapshot.value)
}, withCancelBlock: { error in
print(error.description)
})
In order to optimize this, I changed with .ChildAdded. In this case I get only the single item without the ID associated.
Is it possible to get also the ID of each item using .ChildAdded?
If not, how can I save the ID generated by Firebase into each item? Currently I am saving each item in this way:
let ideasRef = firebase.childByAppendingPath(IdeaStructure.PATH_IDEAS).childByAutoId()
let idea = [
IdeaStructure.FIELD_MESSAGE: message,
IdeaStructure.FIELD_CREATOR_ID: userId,
IdeaStructure.FIELD_CREATION_DATE: NSDate().formattedISO8601
]
ideasRef.setValue(idea)
To get the key of the snapshot, access its key property:
let ideasRef = firebase.childByAppendingPath(IdeaStructure.PATH_IDEAS)
ideasRef.observeEventOfType(.Value, withBlock: { snapshot in
print(snapshot.key)
print(snapshot.value)
}, withCancelBlock: { error in
print(error.description)
})
This and many more topics are covered in Firebase's excellent programming guide for iOS.

Resources