Search code examples
iosswiftfirebasegeofire

List nearby GeoFire locations in tableview


Currently, as my codes below shown, my tableview display everything from Firebase. How do I limit the list to what's nearby?

DataService.dataService.BUSINESS_REF.observeEventType(.Value, withBlock: { snapshot in

        // A snapshot of the businesses data

        self.businesses = []

        if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] {

            for snap in snapshots {

                // Make business array for the tableview
                if let postDictionary = snap.value as? Dictionary<String, AnyObject> {

                    let key = snap.key
                    let business = Business(key: key, dictionary: postDictionary)

                    // Show newest business first
                    self.businesses.insert(business, atIndex: 0)
                }
            }
        }

        // Update the table when there is new data

        self.searchTableView.reloadData()
    }) 

I'm new to iOS programming and the codes above is from a tutorial, I realise I need to make use of GeoFire's GFQuery objects but I just can't figure out where to put this in my code. Thanks in advance!


Solution

  • Figured it out. Hope someone can suggest the better way of doing this.

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    
        firebase = Firebase(url:"https://myapp.firebaseio.com/")
        geoFire = GeoFire(firebaseRef: firebase!.childByAppendingPath("geo"))
    
        let userLocation:CLLocationCoordinate2D = (locationManager.location?.coordinate)!
        let center = CLLocation(latitude: userLocation.latitude, longitude: userLocation.longitude)
        let span = MKCoordinateSpanMake(0.0125, 0.0125)
        let region = MKCoordinateRegionMake(center.coordinate, span)
        let regionQuery = geoFire?.queryWithRegion(region)
    
        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
    
        regionQuery!.observeEventType(GFEventTypeKeyEntered, withBlock: { (key: String!, location: CLLocation!) in
    
            // Check for changes in Firebase database
            DataService.dataService.BUSINESS_REF.queryOrderedByKey().queryEqualToValue(key).observeEventType(.Value, withBlock: { snapshot in
    
                if let snapshots = snapshot.children.allObjects as? [FDataSnapshot]  {
    
                    for snap in snapshots {
    
                        if let postDictionary = snap.value as? Dictionary<String, AnyObject> {
    
                        //let key = snap.key
                        let business = Business(key: key, dictionary: postDictionary)
    
                        self.businesses.insert(business, atIndex: 0)
    
                        }
                    }
                }
    
                self.searchTableView.reloadData()
    
            })
        })
    }