0

I am trying to sort my places by distance from the user. I know how to accomplish this with MKMapItems, yet with my firebase call setup I am unsure how to accomplish this. I have been trying to follow this answer: Swift - Sorting by Nearest Location from Data pulled from Firebase DB yet no luck. I don't know if I will have to change my whole setup or maybe I am just overthinking this?

import UIKit
import Firebase
import MapKit

class RegisteredLocationsTableView: UITableViewController, UISearchResultsUpdating, CLLocationManagerDelegate, NSUserActivityDelegate {

@IBOutlet var followUsersTableView: UITableView!
let searchController = UISearchController(searchResultsController: nil)

var loggedInUser:FIRUser?
var loggedInUserData:NSDictionary?
var usersArray = [NSDictionary?]()
var filteredUsers = [NSDictionary?]()

var locationManager = CLLocationManager()
let distanceFormatter = MKDistanceFormatter()
var locationData: NSDictionary?
var geofences = [CLCircularRegion]()
var nameKeyDict:[String:String] = [:]

var databaseRef = FIRDatabase.database().reference()

override func viewDidLoad() {
    super.viewDidLoad()

    searchController.searchResultsUpdater = self
    searchController.dimsBackgroundDuringPresentation = false
    definesPresentationContext = true
    tableView.tableHeaderView = searchController.searchBar

    locationManager.delegate = self
    locationManager.distanceFilter = kCLLocationAccuracyNearestTenMeters
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.startUpdatingLocation()
    locationManager.stopUpdatingLocation()


    databaseRef.child("Businesses").queryOrdered(byChild: "businessName").observe(.childAdded, with: { (snapshot) in

        let key = snapshot.key
        let snapshot = snapshot.value as? NSDictionary


        snapshot?.setValue(key, forKey: "uid")

        if(key == self.loggedInUser?.uid) {
            print("Same as logged in user, so don't show!")
        } else {
            self.usersArray.append(snapshot)

            //insert the rows
            self.followUsersTableView.insertRows(at: [IndexPath(row:self.usersArray.count-1,section:0)], with: UITableViewRowAnimation.automatic)
        }

    }) { (error) in
        print(error.localizedDescription)
    }
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if searchController.isActive && searchController.searchBar.text != ""{
        return filteredUsers.count
    }
    return self.usersArray.count
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! RegisteredLocationsCell


    let user : NSDictionary?

    if searchController.isActive && searchController.searchBar.text != ""{

        user = filteredUsers[indexPath.row]
    } else {
        user = self.usersArray[indexPath.row]
    }

    cell.configure(businessName: user?["businessName"] as! String, businessStreet: user?["businessStreet"] as! String, businessCity: user?["businessCity"] as! String, businessState: user?["businessState"] as! String, businessDistance: user?["businessDistance"] as! String )

    return cell
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    super.prepare(for: segue, sender: sender)
    if segue.identifier == "BusinessProfiles" {
        // gotta check if we're currently searching
        if self.searchController.isActive && searchController.searchBar.text != "" {
            if let indexPath = tableView.indexPathForSelectedRow {
                let user = filteredUsers[indexPath.row]
                let controller = segue.destination as? BusinessProfilesViewController
                controller?.otherUser = user
            }
        } else {
            if let indexPath = tableView.indexPathForSelectedRow {
                let user = usersArray[indexPath.row]
                let controller = segue.destination as? BusinessProfilesViewController
                controller?.otherUser = user
            }
        }
    }
}


func updateSearchResults(for searchController: UISearchController) {

    filterContent(searchText: self.searchController.searchBar.text!)
}

func filterContent(searchText:String) {
    self.filteredUsers = self.usersArray.filter { user in

        let username = user!["businessName"] as? String

        return(username?.lowercased().contains(searchText.lowercased()))!
    }
    tableView.reloadData()
}

}
Lukas Bimba
  • 817
  • 14
  • 35
  • please share your firebase structure. – Nishant Bhindi Aug 22 '17 at 13:16
  • What does your data look like? How do you plan to calculate the distance? On the server side or the client side? In general I think you want something like ref.queryOrderedByChild("zipcode?").queryStartingAtValue("usersZipCode") check out some example here: https://stackoverflow.com/questions/38757248/firebase-query-sort-order-in-swift and here: https://stackoverflow.com/questions/37343375/firebase-querying – DoesData Aug 22 '17 at 13:17
  • I have the Longitude and Latitude stored for each location and wan to use those to convert the distance between the location and the users location – Lukas Bimba Aug 23 '17 at 02:19

0 Answers0