Swift Firebase - 按用户距离排序数组

时间:2017-08-22 12:37:28

标签: swift uitableview firebase location cllocationdistance

我正在尝试按距离用户排序我的位置。我知道如何使用MKMapItems完成此任务,但是通过我的firebase调用设置,我不确定如何实现这一点。我一直试图遵循这个答案:Swift - Sorting by Nearest Location from Data pulled from Firebase DB但没有运气。我不知道我是否需要改变整个设置,或者我只是想过这个?

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()
}

}

0 个答案:

没有答案