gpt4 book ai didi

ios - 如何在 Swift 中写入 Firebase ref 的最后一个 child ?

转载 作者:行者123 更新时间:2023-11-28 06:27:50 25 4
gpt4 key购买 nike

我正在努力以所需的方式将数据写入 Firebase。

情况:我想为每个用户存储多个“行程”。每个“行程”都包含带有纬度、经度、高度和时间戳的位置。在某些情况下,我想在最近的“旅行”中添加一个新位置。

数据结构如下:

- root
-- users
--- userID
---- trips
------ trip1
------- location
------ trip2
------- location

将位置添加到最近的行程(在本例中为 trip2)的最佳方式是什么?

我曾希望类似这样的东西是可能的:

func setupFirebase() {
ref = FIRDatabase.database().reference()
userRef = ref.child("users")

userID = FIRAuth.auth()?.currentUser?.uid
tripsRef = self.userRef.child(userID!).child("trips")
currentTripRef = tripsRef.queryLimited(toLast: 1)

}

然后我可以简单地去:

currentTripRef.child(dateString).setValue([
"timestamp": dateString,
"lat": lat,
"lng": lng,
"alt": alt
])

无论我需要写些什么。这显然不是正确的方法,但我似乎无法弄清楚正确的方法是什么。

我想我可以观察我的 tripsRef,获取一组键,然后在该观察函数内部用最后一个键写入子引用。但这听起来效率不高。

有什么解决办法吗?提前致谢!

最佳答案

首先,请记住最佳做法是取消节点名称与数据的关联。您可能正在这样做,但想强调这一点。

这是处理用户及其行程的建议结构

root
users
uid_0
name: "Jamie"
uid_1
name: "Adam"
trips
-Yijaisioaooisd
user_id: "uid_0"
trip_number: 1
trip_name: "France"
locations
-Yuijiaissso
location_name: "Bordeaux"
stop_number: 1
-Yijs9ojnas9
location_name: "Burgundy"
stop_number: 2
-Yijispoais
location_name: "Châteauneuf-du-Pape"
stop_number: 3

如果您想为 uid_0 的法国之旅添加另一个停靠点/位置,引用是

let locationsRef = rootRef.child("trips").child("-Yijaisioaooisd").child("locations")

然后

let anotherLocationRef = locationsRef.childByAutoId()
let stopDict = ["location_name": "Médoc", "stop_number": 4]
locationsRef.setValue(stopDict)

话虽这么说,但在某些情况下,您可能希望对数据进行非规范化并分解位置(用于查询等)

那就是

locations
trip_id: "-Yijaisioaooisd"
locations:
-Yuijiaissso
location_name: "Bordeaux"
stop_number: 1
-Yijs9ojnas9
location_name: "Burgundy"
stop_number: 2
-Yijispoais
location_name: "Châteauneuf-du-Pape"
stop_number: 3

根据评论,添加一些额外的信息:

如果您想为 uid_0 的最新行程添加另一个停靠点,有多种选择,实际答案取决于数据结构。

使用 queryLimitedToLast,可以查询位置节点中的最后一个停靠点,以获取停靠点编号(上例中为 3),您可以在其中递增它,然后写出下一停靠点。如果您知道父键 -Yijaisioaooisd,这将起作用,因为 ref 将是 -Yijaisioaooisd/locations。

如果您不知道父键,您可以通过在 trips 节点上查询等于 uid_0 的 user_id 轻松获得它。这将返回一个快照。然后 snapshot.key 将提供 -Yijaisioaooisd 父 key 。

关于ios - 如何在 Swift 中写入 Firebase ref 的最后一个 child ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41333862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com