Swift - 根据从Firebase DB提取的数据的最近位置进行排序 [英] Swift - Sorting by Nearest Location from Data pulled from Firebase DB

查看:189
本文介绍了Swift - 根据从Firebase DB提取的数据的最近位置进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从我的firebase后端检索数据 - 每个条目都有一个用户名lat和long。从查看其他的stackoverflow问题,我看到CoreLocation应该按照距离我们尝试使用的距离(或者距离(from :))的方法进行排序。它似乎没有按预期工作。

 导入UIKit 
导入Firebase
导入FirebaseDatabase
导入MapKit
导入CoreLocation

类RequestVC:UITableViewController,CLLocationManagerDelegate {

var locationManager = CLLocationManager()
var sellerUserNames = [String] ()
var requestLocations = [CLLocationCoordinate2D]()

override func prepare(for segue:UIStoryboardSegue,sender:Any?){
if segue.identifier ==backToMain {
self.navigationController?.navigationBar.isHidden = true
}
}

覆盖func viewDidLoad(){
super.viewDidLoad()

locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()

let databaseRef = FIRD观察(FIRDataEventType.childAdded,其中:{(FIRDataSnapshot)in

如果let data = FIRDataSnapshot.value如? NSDictionary {
如果让name = data [Constants.NAME] as?字符串{
如果让lat = data [纬度]为? Double {
如果让long = data [longitude]为? Double {

print(\(self.sellerUserNames)Location:Latitude:\(lat),Longitude:\(long))

self.sellerUserNames .append(name)
self.requestLocations.append(CLLocationCoordinate2D(latitude:lat,longitude:long))

self.tableView.reloadData()

}





$ b func locationManager(_ manager:CLLocationManager,didUpdateLocations locations:[CLLocation]){
}

覆盖func numberOfSections(在tableView:UITableView中) - > Int {
return 1
}

覆盖func tableView(_ tableView:UITableView,numberOfRowsInSection section:Int) - > Int {
return sellerUserNames.count
}


覆盖func tableView(_ tableView:UITableView,cellForRowAt indexPath:IndexPath) - > UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier:cell,for:indexPath)
let location = locationManager.location?.coordinate

let buyerLocation = CLLocation(latitude:(location?.latitude)!,longitude:(location?.longitude)!)
let sellerLocation = CLLocation(纬度:requestLocations [indexPath.row] .latitude,longitude:requestLocations [indexPath.row ] .longitude)

let distance = buyerLocation.distance(from:sellerLocation)/ 1000

roundDistance = round(距离* 100)/ 100

let distanceInMiles = roundedDistance * 0.621
let roundedDistanceInMiles = round(distanceInMiles * 1000)/ 1000


cell.textLabel?.text = sellerUserNames [indexPath.row] + - \(roundedDistanceInMiles)miles away

return cell
}
}


解决方案

你可以尝试使 GeoFire 正常工作。它不适用于cocoapods,虽然有解决方法。


I am trying to retrieve data from my firebase backend - Each entry has a username, lat and long. From looking at other stackoverflow questions, I see that CoreLocation is supposed to sort by nearest location with it's distancefrom (or rather, distance(from:)) method, which I tried to use. It doesn't seem to be working as intended. I'm wondering what I'm doing wrong.

import UIKit
import Firebase
import FirebaseDatabase
import MapKit
import CoreLocation

class RequestVC: UITableViewController, CLLocationManagerDelegate {

    var locationManager = CLLocationManager()
    var sellerUserNames = [String]()
    var requestLocations = [CLLocationCoordinate2D]()

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "backToMain" {
            self.navigationController?.navigationBar.isHidden = true
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()

        let databaseRef = FIRDatabase.database().reference()
        databaseRef.child("Sell_Request").observe(FIRDataEventType.childAdded, with: { (FIRDataSnapshot) in

            if let data = FIRDataSnapshot.value as? NSDictionary {
                if let name = data[Constants.NAME] as? String {
                    if let lat = data["latitude"] as? Double {
                        if let long = data["longitude"] as? Double {

                            print("\(self.sellerUserNames) Location: Latitude: \(lat), Longitude: \(long)")

                            self.sellerUserNames.append(name)
                            self.requestLocations.append(CLLocationCoordinate2D(latitude: lat, longitude: long))

                            self.tableView.reloadData()

                        }
                    }
                }
            }
        })
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        }

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

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sellerUserNames.count
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        let location = locationManager.location?.coordinate

        let buyerLocation = CLLocation(latitude: (location?.latitude)!, longitude: (location?.longitude)!)
        let sellerLocation = CLLocation(latitude: requestLocations[indexPath.row].latitude, longitude: requestLocations[indexPath.row].longitude)

        let distance = buyerLocation.distance(from: sellerLocation) / 1000

        let roundedDistance = round(distance * 100) / 100

        let distanceInMiles = roundedDistance * 0.621
        let roundedDistanceInMiles = round(distanceInMiles * 1000) / 1000


        cell.textLabel?.text = sellerUserNames[indexPath.row] + " - \(roundedDistanceInMiles) miles away"

        return cell
    }
}

解决方案

You could try do make GeoFire work. It doesn't work with cocoapods, though there are workarounds.

这篇关于Swift - 根据从Firebase DB提取的数据的最近位置进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆