Search Firebase Query with array of unique keys - ios

I have my schema set as follows.
Now i want to send the a string chinohills7leavescafe101191514.19284 and want to check if there is any string in the Chino Hills or not.
I am confused to make any search query because i have not stored above string in fixed childKey
I know the schema should be like this but i cannot change the schema.
leaves-cafe
codes
Chino Hills
-Kw0ZtwrPjyNh1_HJrkf
codeValue: "chinohills7leavescafe101191514.19284"

You're looking for queryOrderedByValue. It works the same ways as queryOrderedByChild and allows you to use queryEqualToValue to achieve the result you need since you can't alter your current schema.
Here's an example
// warning: untested code - just illustrating queryOrderedByValue
let ref = Database.database().reference().child("leaves-cafe").child("codes").child("Chino Hills")
let queryRef = ref.queryOrderedByValue().queryEqual(toValue: "chinohills7leavescafe101191514.19284")
queryRef.observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.exists() {
print("value does exists")
} else {
print("value doesn't exist")
}
})
Your alternative option is to iterate over all nodes and check if the value exists manually as 3stud1ant3 suggested. However, note that this approach is both costy and a security risk. You would be downloading potentially a lot of data, and generally you shouldn't load unneeded data (especially if they're sensitive information, not sure if that's your case) on device; it's the equivalent of downloading all passwords off a database to check if the entered one matches a given user's.

Related

Display the name of a user using Firebase

What I want to do is to make a top header in the app with the name of the user displayed in a label. I know everything to do this except how to reference their name. To give more clarity this is what I want (even though this doesn't work in the newest version of xcode);
let userName = Auth.auth().currentUser.name
// so this is the string of the users name
I know this seems really simple and there is probably an easy way to do it that I'm not sure of. Thanks for the help!
This is how I access my firebase realtime database and read from it:
let ref = Database.database().reference()
ref.child("Username").observeSingleEvent(of: .value) {(snapshot:DataSnapshot) in
let userName = snapshot.value as? String
Print(userName)
}
Instead of where I put "Username", you can replace this with the name of the node under which the value you want to output is stored. And if this node is the child node of another, you can continue to add .child("XXX") to the line of code.
e.g.
ref.child("Account").child("Username").observeSingleEvent(of: .value) {(snapshot:DataSnapshot) in
It's tucked away a little, in providerData, which is an instance of UserInfo...
let user = Auth.auth().currentUser
let userName = user.providerData.displayName

Swift Firebase Query - No Results in Snapshot

I am trying to query our LCList object by the "name" value, as shown in this image. The name key is just on the next level below the object. There are no additional levels to any of its other values.
The code I am using to do the query is: (Keeping in mind listsRef points to the LCLList object)
listsRef.queryOrderedByKey()
.queryStarting(atValue: name)
.observeSingleEvent(of: .value, with: { snapshot in
The snapshot from this query comes back with nothing in its value. I have tried ordering the results by the name value as well, with the same result. I have inspected the values returned with only the queryOrderedByKey() method call, and they match what is in the database. The issue is obviously with the .queryStarting(atValue:) method call.
I'm really puzzled by why this is not working as the same query pointed to our LCLUser object, with nearly the same structure, does get results. The two objects exist at the same level in the "Objects" directory seen in the previous image.
Any help at this point would be appreciated. I'm sure there's something simple I'm missing.
That query won't work for the Firebase structure shown in the question.
The query you have is as follows, I have added a comment on each line detailing what each line does
listsRef.queryOrderedByKey() //<- examine the key of each child of lists
.queryStarting(atValue: name) //<- does that keys' value match the name var
.observeSingleEvent(of: .value, with: { snapshot in //do it once
and your current data looks like this
Objects
LCLLists
node_x
creator: "asdasa"
name: "TestList3"
node_y
creator: "fgdfgdfg"
name: "TestList"
so what's happening here is the name var (a string) is being compared to the value of each key (a Dictionary) which cannot be equal. String ≠ Dictionary
key value
["node_x": [creator: "asad", name: "TestList3"]
For that query to work, your structure would need be be like this
Objects
LCLLists
node_x: "TestList3"
node_y: "TestList"
My guess is you want to stick with your current structure so, suppose we want to query for all names that are 'TestList' using your structure
let ref = self.ref.child("LCLLists") //self.ref is a class var that references my Firebase
let query = ref.queryOrdered(byChild: "name").queryEqual(toValue: "TestList")
query.observeSingleEvent(of: .value, with: { snapshot in
print(snapshot)
})
and the result is a printout of node_y
node_y
creator: "fgdfgdfg"
name: "TestList"

Swift: Searching Firebase Database for Users

I have been looking all over the internet and Stack overflow but haven't found anything that I understood well enough to implement into my solution.
There are many similar questions out there but none of the proposed solutions worked for me, so I'll ask you guys.
How do I search my Firebase database for usernames in swift?
In my app I have a view that should allow the user to search for friends in the database. Results should be updated in real time, meaning every time the user types or deletes a character the results should update. All I have so far is a UISearchBar placed and styled with no backend code.
Since I don't really know what is needed to create such a feature it would be cool if you guys could tell me what you need to tell me exactly what to do. (Database Structure, Parts of Code...). I don't want to just copy and paste useless stuff on here.
I would really appreciate the help.
EDIT:
This is my database structure:
"users"
"uid" // Automatically generated
"goaldata"
"..." // Not important in this case
"userdata"
"username"
"email"
"country"
"..." // Some more entries not important in this case
Hope I did it right, didn't really know how to post this on here.
Suppose the Firebase structure is like this
Example 1 :
users
-> uid
->otherdata
->userdata
->username : "jen"
-> other keys
-> uid2
->otherdata
->userdata
->username : "abc"
-> other keys
And to query based on username, we need to query on queryOrdered(byChild: "userData/username"). queryStarting & queryEndingAt , fetches all the names starting from "je" and this "\uf8ff" signifies * (any) .
let strSearch = "je"
baseRef.child("users").queryOrdered(byChild: "userData/username").queryStarting(atValue: strSearch , childKey: "username").queryEnding(atValue: strSearch + "\u{f8ff}", childKey: "username").observeSingleEvent(of: .value, with: { (snapshot) in
print(snapshot)
}) { (err) in
print(err)
}
If the username is directly below the users node, then try this
Example 2 :
users
-> uid
->username : "jen"
-> other keys
-> uid2
->username : "abc"
-> other keys
The query will be restructured as below,
let strSearch = "je"
baseRef.child("users").queryOrdered(byChild: "username").queryStarting(atValue: strSearch).queryEnding(atValue: strSearch + "\u{f8ff}").observeSingleEvent(of: .value, with: { (snapshot) in
print(snapshot)
})
Please note this method is case-sensitive . The search results for search String = "je" and "Je" will be different and the query will match the case.

Get a limited number of records in Firebase

I would like to query Firebase for records that match my conditions, but I want to only get a few of them. I am using Swift. Is this possible? For example, I have a query like this:
firebaseReference.child("array").queryOrdered(byChild: "userType").queryEqual(toValue: "family").observe(.value, with: { (snapshotVec) -> Void in
Storage.shared.numFamsInVec = snapshotVec.childrenCount
}
This will retrieve all the records whose userType is family, but say I only want to get half of them. How do I do this?
It certainly is. The magic is in the Firebase documentation for filtering data on iOS:
firebaseReference
.child("array")
.queryOrdered(byChild: "userType")
.queryEqual(toValue: "family")
.queryLimited(toFirs: 10)
.observe(.value, with: { (snapshotVec) -> Void in
Storage.shared.numFamsInVec = snapshotVec.childrenCount
}
Also see the Firebase reference documentation, which contains the magic incantation for Swift 3.

Check Firebase for existing data before overwriting?

I have the following data in Firebase:
devices
iphone5
date_created: "1456183905"
I'm trying to determine if "date_created" exists, and if it doesn't then create it.
I read about snapshots, but is there an easier way to check Firebase to see if this data exists? What I have now is using snapshots, but it is tied to an event handler. Can't I just do a basic query to see if this entry exists or not?
Thanks.
You can test if a value exists in your Swift code, by:
let ref = Firebase(url: "https://stackoverflow.firebaseio.com/35570687")
ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
if (!snapshot.exists()) {
ref.setValue([".sv": "timestamp"])
}
else {
print("already exist")
}
})
But since this is only client-side, there is a chance that two clients will run the code at almost the exact time and both end up writing the timestamp. In the snippet above that wouldn't be a problem, but in real use-cases this sort of race condition might be unwanted.
As Andre commented, you can validate this in your security rules:
"date_created": {
".write": "!data.exists() || data.val() == newData.val()"
This validates that either this is the first time you write date_created (so the data won't exist yet) or otherwise that the value is unchanged.

Resources