Reputation: 41
I have a firebase database in my app, here is a screenshot of it:
And I need to filter my results using this controller
so I need to compare from
`ref.observe(.value, with: {snapshot in
if (snapshot.value is NSNull){
print("not found")
}else{
for child in (snapshot.children) {
let snap = child as! DataSnapshot
let dict = snap.value as! AnyObject
let latt = dict["lat"]
let lngt = dict["lng"]
let sext = dict["sex"]
let statust = dict["status"]
let aget = dict["age"]
if self.searchSex.selectedSegmentIndex == 0{
self.sexG = "Male"}
else if self.searchSex.selectedSegmentIndex == 1{
self.sexG = "Female"
}
if (self.sexG == sext as! String && Int(searchAgeFrom.value) <= Int(aget) <= Int(searchAgeTo.value)))
{
}
}
}
})
`
I don't know how to filter results from dataSnapshot, I always get an errors. Here, I perform my searching, in ????? I don't know how search for selected value from pickerView:
if (self.sexG == sext as! String && Int(searchAgeFrom.value) <= Int(aget) <= Int(searchAgeTo.value)) && ?????)
{
}
Upvotes: 1
Views: 707
Reputation: 72460
First of all your if condition is not correct as of with searchAgeTo.value
you are not comparing with any value also instead of casting snap.value
to AnyObject
cast it to proper dictionary in your case it is [String:Any]
.
Now to get the pickerView
selected value you can use instance method selectedRow(inComponent:)
or also use UIPickerViewDelegate
method didSelectRow
.
let selectedIndex = yourPickerView.selectedRow(inComponent: 0)
let selectedValue = yourPikcerArray[selectedIndex]
Now compare this in if condition this way.
for child in (snapshot.children) {
let snap = child as! DataSnapshot
let dict = snap.value as! [String:Any]
let latt = dict["lat"]
let lngt = dict["lng"]
let sext = dict["sex"] as! String
let statust = dict["status"] as! String
let aget = dict["age"]
if self.searchSex.selectedSegmentIndex == 0 {
self.sexG = "Male"
}
else {
self.sexG = "Female"
}
let selectedIndex = yourPickerView.selectedRow(inComponent: 0)
let selectedValue = yourPikcerArray[selectedIndex]
if (self.sexG == sext && Int(searchAgeFrom.value) >= Int(aget) && Int(aget) <= Int(searchAgeTo.value) && selectedValue == statust) {
//Handle here
}
}
But instead of filtering Firebase
data this way better way is you can store all the data in some main array and than filter that main array according to your filter so that you will not need to observe Firebase
data every time when you change your filter value. Also make one custom class or struct to manage all your Firebase data with array of that custom object.
Upvotes: 1
Reputation: 3272
I believe you have erors in unwrapping of snapshot
.
Try this:
let dict = snap.value as! [String: AnyObject]
let latt = dict["lat"] as! Double
let lngt = dict["lng"] as! Double
// etc..
Hope it helps
Upvotes: 2