Reputation: 12857
I am storing users' locations and items assigned to them in different tables. Think it as there are items user is selling and the location of the item is assigned to the user.
I am using radius to retrieve users' locations. I can retrieve all items if I use 10km radius. However, I want to separate items to each km, such as:
- 1km
- Guitar
- Sofa
- 2km
- Citroen
- Renault
- Piano
The problem is that the query works like this so if I use '10km' as radius, it fetches everything from 0 to 10km:
let circleQuery = geoFire.queryAtLocation(center, withRadius: 10)
So it logs like:
- 1km
- Guitar
- Sofa
- 2km
- Guitar
- Sofa
- Citroen
- Renault
- Piano
I thought one way could be using a for loop and storing it to a dictionary.
The approach I tried:
var items = [Int: AnyObject]()
func retrieveItems() {
let center = CLLocation(latitude: userLatitude, longitude: userLongitude)
for index in 1...25 {
let circleQuery = geoFire.queryAtLocation(center, withRadius: Double(index))
// after everything fetched
self.items = [
index : [itemId : value]
]
// So, 'index' would be km
// 'itemId' is the id in db
// 'value' would be 'key: value'
// the database table looks like:
// - itemId:
// key:value
// key:value
}
}
Example dictionary tree:
let dictionary = [
1 : [
"item1" : ["key": "value", "key": "value"],
"item2" : ["key": "val", "key": "val"],
],
2 : [
"item3" : ["key": "val", "key": "val"],
"item4" : ["key": "val", "key": "val"],
"item5" : ["key": "val", "key": "val"],
]
]
As every time the index is increasing, it's fetching starting from 0km, so it's re-fetching already fetched stuff. But, using the dictionary, maybe I can make a check and if the 'itemId' is already in the dictionary, don't re-add it.
My question is, is there a way I can check if the 'itemId' is already added in the dictionary using above approach, so I don't add already added items? What is the way of achieving it in complex multidimensional dictionary like the one above?
Update: I tried something like this to check if the "itemId" exists
if self.events.indexForKey(index) != nil {
let radius = self.events[index]! as! Dictionary<String, AnyObject>
print("km exists")
} else {
print("distance doesn't exist")
self.items = [
index : [itemId : value]
]
}
But it's always going inside else
bit.
Upvotes: 0
Views: 158
Reputation: 4422
If you don't want to get duplicate events, you should just do a single query at 25 km, retrieve all keys, and then use client-side logic to filter those out into individual km groups. You can compute the distance between the returned keys coordinates and the center of your query using some math.
Upvotes: 1