Swift Firebase Query - No Results in Snapshot - ios

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"

Related

Search Firebase Query with array of unique keys

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.

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.

Firebase QueryOrderedByChild along with EqualToValue and StartingAtValue Combination

I am trying to query Firebase by a Child that is equal to a certain value BUT start the snapshot at a specific post key.
Data Structure:
projectName
-posts
-postKey1
-storeId: 1
-postKey2
-storeId: 2
-postKey3
-storeId:3
-postKey4
-storeId:2
-postKey5
-storeId:3
-postKey6
-storeId:2
Example:
I am trying to queryOrderedByChild("storeId") with queryEqualToValue("2") BUT I would like the snapshot to start at "postKey4" when it is returned in its order.
My Current Query:
ref.queryOrderedByChild("storeId").queryEqualToValue("\(myId)").observeEventType(.Value, withBlock: {snapshot in
I know that you can't call queryEqualToValue: after queryStartingAtValue, queryEndingAtValue or queryEqualToValue after previously called but I need that queryEqualToValue to get my storeId. Any help is greatly appreciated!
You can pass a second argument into queryStartingAtValue that specifies the key at which to start.
ref.queryOrderedByChild("storeId")
.queryStartingAtValue(2, childKey: "postKey4")
.queryEndingAtValue(2)
.observeEventType(.Value, withBlock: {snapshot in
for childSnapshot in snapshot.children {
print(childSnapshot.key!!
}
})
This prints:
postKey4
postKey6
I must admit this is the first time I use the second argument to queryStartingAtValue, so I might not understand it completely yet.
The reason you can't use queryEqualToValue is that that will only return a single key, which is not what you want.

How to get all results from a Firebase Query in one block

I'm having a hard time working with Firebase query results. With the following code:
ref.queryOrderedByChild("gender")
.queryEqualToValue("female")
.observeEventType(.ChildAdded, withBlock: { snapshot in
print("result: \(snapshot) ")
})
The "result" is printed 3 times. I would expect a single array of all of the results (similar to a query on Parse) versus this being printed 3 separate times.
The end goal here is to append all of the results to an Array. However, I don't know how to do that, since I can't see any way of knowing how many elements will come back from the server.
I assume there must be something simple I am missing here.
It appears it was something simple I was missing. Changing the event type from .ChildAdded to .Value resolves the issue. Hopefully this will help someone else...
var resultArray:[AnyObject] = []
ref.queryOrderedByChild("gender")
.queryEqualToValue("female")
.observeEventType(.Value, withBlock: { snapshot in
for item in snapshot.children{
resultArray.append(item)
}
print("Results Array: \(resultArray)")
print("Results Array Count: \(resultArray.count)")
})

More efficient way to retrieve Firebase Data?

I have a hierarchical set of data that I want to retrieve information from Firebase. Below is how my data looks:
However, my issue is this: Upon looking at how the data is structured, when I want to grab the name or object id of an attendee, I have to perform the following code:
func getAttendees(child: NSString, completion: (result: Bool, name: String?, objectID: String?) -> Void){
var attendeesReference = self.eventsReference.childByAppendingPath((child as String) + "/attendees")
attendeesReference.observeEventType(FEventType.ChildAdded, withBlock: { (snapshot) -> Void in
//Get the name/object ID of the attendee one by one--inefficient?
let name = snapshot.value.objectForKey("name") as? String
let objectID = snapshot.value.objectForKey("objectID") as? String
if snapshot != nil {
println("Name: \(name) Object ID: \(objectID)")
completion(result: true, name: name, objectID: objectID)
}
}) { (error) -> Void in
println(error.description)
}
}
Now this goes through every attendee child and grabs the name and object id one by one. When the function completes, I store each value into a dictionary. Upon doing so, this function is called multiple times and can be very slow especially when going to/from a database so many times. Is there a more efficient way to do this? I have tried to look into FEeventType.Value but that seems to return everything within the attendees child, when all I really want are the name and objectID of each attendee stored into some sort of dictionary. Any help would be appreciated. Thanks!
One of the golden rules of Firebase is to only nest your data when you always want to retrieve all of it. The reason for this rule is that Firebase always returns a complete node. You cannot partially retrieve some of the data in that node and not other data.
The Firebase guide on structuring data, says this about it:
Because we can nest data up to 32 levels deep, it's tempting to think that this should be the default structure. However, when we fetch data at a location in our database, we also retrieve all of its child nodes. Therefore, in practice, it's best to keep things as flat as possible, just as one would structure SQL tables.
You should really read that entire section of the docs, since it contains some pretty good examples.
In your case, you'll need to modify your data structure to separate the event attendees from the event metadata:
events
-JFSDFHdsf89498432
eventCreator: "Stephen"
eventCreatorId: 1764137
-JOeDFJHFDSHJ14312
eventCreator: "puf"
eventCreatorId: 892312
event_attendees
-JFSDFHdsf89498432
-JSAJKAS75478
name: "Johnny Appleseed"
-JSAJKAS75412
name: "use1871869"
-JOeDFJHFDSHJ14312
-JaAasdhj1382
name: "Frank van Puffelen"
-Jo1asd138921
name: "use1871869"
This way, you can retrieve the event metadata without retrieving the attendees and vice versa.

Resources