首页 > 解决方案 > 使用swift构建来自firebase的实时位置数据请求

问题描述

因此,我试图检索“配对用户”的位置(即不是当前用户,而是当前用户的联系人)并监控行进距离和相对于当前用户的距离。使用下面的代码时,我只能检索具有相同位置的多个条目的列表,而不是始终只获取“配对用户”的新位置更新。

func retrieveLocations() {
        let locationDB = Database.database().reference().child("Locations").child("nameOfUser")

locationDB.queryLimited(toLast: 1).observe(.childAdded)
            { (snapshot) in

        let snapshotValue = snapshot.value as! Dictionary<String,Any>

        let lats = snapshotValue["Lat"]
        let longs = snapshotValue["Lon"]
        let timeOf = snapshotValue["Time"]
        let sender = snapshotValue["Sender"]


  let otherUsersLocations = CLLocation(latitude: CLLocationDegrees(truncating: lats! as! NSNumber), longitude: CLLocationDegrees(truncating: longs! as! NSNumber), timestamp: timeOf as! Int)
print("Latitude: \(otherUsersLocations.coordinate.latitude), Longitude: \(otherUsersLocations.coordinate.longitude), Time: \(timeOf), Sender: \(sender)")

我稍后在用于更新当前用户位置的同一个函数中调用该函数。下面的代码用于将当前用户位置更新到 firebase。Firebase 数据库屏幕截图

let locationDictionary = [

            "Sender": Auth.auth().currentUser?.email,
            "Lat": latitude,
            "Lon": longitude,
            "Speed": speed,
            "Time": ServerValue.timestamp()

            ] as [String : Any]


        locationDB.childByAutoId().setValue(locationDictionary) {
            (error, reference) in
            if error != nil {
                                print(error!)
                            }
                            else {

                            }
        }


    }

    retrieveLocations()

我尝试创建一个新的“LocationModel”对象,但在使用从 firebase 检索到的数据向 LocationModel 类型的字典提供时遇到了麻烦。所以我的目标是从“现在”检索配对用户的位置数据数组/字典,然后测量到 currentUser 的距离。

我已经坐了一段时间,所以我非常感谢任何建议。非常感谢!

标签: swiftfirebasefirebase-realtime-databaselocationdata-retrieval

解决方案


推荐阅读