GeoFire Swift 3 - 保存和更新坐标 [英] GeoFire Swift 3 - Saving and Updating Coordinates
问题描述
我正在尝试使用GeoFire将坐标存储到Firebase数据库中。
I'm trying to store coordinates into Firebase Database using GeoFire.
我不确定如何更新新坐标,因为它们每秒都会更改/更新。使用 childByAutoId
,它会为每个Bike生成一个新的唯一ID。
I'm unsure how to update the new coordinates as they will be changed/updated every second. With the childByAutoId
, it is generating a new unique ID for each Bike.
如何引用这个独特的Bike ID?例如,用户将被 FIRAuth.auth()?currentUser?.uid
调用。这可能吗?
How do I reference this unique Bike ID? For instance, the user would be called by FIRAuth.auth()?.currentUser?.uid
. Is this possible?
let geofireRef = FIRDatabase.database().reference().child("Bike").childByAutoId()
let geoFire = GeoFire(firebaseRef: geofireRef)
var data = geoFire?.setLocation(CLLocation(latitude: userIncrementLat, longitude: userIncrementLong), forKey: "BikeId")
我的Firebase数据库结构看起来像......
My Firebase Database Structure will look like...
Root
1. Bike
2. UniqueUID Number (Firebase)
3. BikeId
4. g
l
5. 0:
1:
推荐答案
这是我的Firebase数据库结构,用于更新用户的位置,并在附近的用户身上显示以在地图上显示:
This is my Firebase DB structure for update users location by time and retrive the nearby users to show on map:
db-root
"users" : {
<userUID> : {
"someKey" : "someValue",
...
}
}
"users_location" : {
<userUID> : {
<geofireData> ...
}
}
使用的Vars:
let ref = FIRDatabase.database().reference()
let geoFire = GeoFire(firebaseRef: ref.child("users_location"))
更新记录的用户位置:
func updateUserLocation() {
if let myLocation = myLocation {
let userID = FIRAuth.auth()!.currentUser!.uid
geoFire!.setLocation(myLocation, forKey: userID) { (error) in
if (error != nil) {
debugPrint("An error occured: \(error)")
} else {
print("Saved location successfully!")
}
}
}
}
要查找附近的用户,我使用 findNearbyUsers
函数。找到附近的用户并将 nearbyUsers
数组保存到用户的UID密钥中非常有用。 observeReady
函数在查询完成后执行,并使用UID检索用户详细信息(我使用此信息在地图上显示用户详细信息)。
To find nearby user I use the findNearbyUsers
function. It' useful to find the nearby users and save into nearbyUsers
array the UID key of the the users. The observeReady
function is executed after the query completion and uses the UID to retrieve the users details (I use this to show users details on map).
func findNearbyUsers() {
if let myLocation = myLocation {
let theGeoFire = GeoFire(firebaseRef: ref.child("users_location"))
let circleQuery = theGeoFire!.query(at: myLocation, withRadius: radiusInMeters/1000)
_ = circleQuery!.observe(.keyEntered, with: { (key, location) in
if !self.nearbyUsers.contains(key!) && key! != FIRAuth.auth()!.currentUser!.uid {
self.nearbyUsers.append(key!)
}
})
//Execute this code once GeoFire completes the query!
circleQuery?.observeReady({
for user in self.nearbyUsers {
self.ref.child("users/\(user)").observe(.value, with: { snapshot in
let value = snapshot.value as? NSDictionary
print(value)
})
}
})
}
}
希望它有帮助
这篇关于GeoFire Swift 3 - 保存和更新坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!