Swift - 从 Firebase DB 中提取的数据按最近位置排序

标签 swift firebase firebase-realtime-database cllocation

我正在尝试从我的 firebase 后端检索数据 - 每个条目都有一个用户名、纬度和经度。通过查看其他 stackoverflow 问题,我发现 CoreLocation 应该使用我尝试使用的 distancefrom(或者更确切地说,distance(from:)) 方法按最近的位置排序。它似乎没有按预期工作。我想知道我做错了什么。

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

最佳答案

你可以试试 make GeoFire工作。尽管有变通办法,但它不适用于 cocoapods。

关于Swift - 从 Firebase DB 中提取的数据按最近位置排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42448800/

相关文章:

ios - 在 URLSession.shared.dataTask 中执行 SegueWithIdentifier(带有 : url)

ios - 如何修改包含 '-'作为单词字符的单词边界

swift - SpriteKit : Scaling Does Not Work Correctly

ios - 复杂的 Swift 扩展

firebase - 参数类型 'Object?' 无法分配给参数类型 'Map<String, dynamic>'

java - 无法解析 com.google.firebase :firebase-database:11. 8.0

firebase - 使用 .info/connected 测试 firebase 连接

javascript - 如何查询从 Firebase 实时数据库获取的 ionic 3 结果?

ios - Swift 函数从异步 firebase 调用返回值

android - 如何使用Firebase数据库和Firebase通知为聊天应用程序构建通知系统