ios - 从 Firebase 中的最后一个 child 那里获取 key

标签 ios firebase firebase-realtime-database

我需要能够从我在 Firebase 上的数据库中随机选择一些数据。为此,为了避免下载整个数据库,我想创建一个条目,其中包含一个由 unsigned int 表示的键,如下图所示:

enter image description here

我的问题是,如何检索最后添加的项目的 key ?

我试过:

ref.queryOrderedByKey().queryLimited(toFirst: 1).observeSingleEvent(of: .value, with: { [unowned self] snapshot in
    let id: UInt64
    if snapshot.exists(), let child = snapshot.children.nextObject() as? FIRDataSnapshot {
        id = UInt64(child.key)!
    } else {
        id = 1
    }
})

但是 UInt64(child.key)!,无论我使用 queryLimited(toFirst:) 还是 queryLimited(toLast:),总是返回1.

我做错了什么?

最佳答案

您的查询返回第一个结果,该结果具有关键字 1。您正在寻找 queryLimited(toLast: 1)

此外,在大多数情况下,您应该 avoid numeric, sequential keys in distributed data .

关于ios - 从 Firebase 中的最后一个 child 那里获取 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39713585/

相关文章:

javascript - 当 Firebase 自动生成 Key 时,是否可以更新子项的数据?

ios - 如何使用 presentViewController 与刚刚显示的 View 进行交互?

ios - 如何获取键值并在字典的键中应用条件?

firebase - 如何从 Cloud Function 调用其他 Cloud Firebase Functions

java - 如何使用 Firebase 中的网站用户注册详细信息通过 Android 应用程序登录用户?

android - Firebase 任务尚未完成

android - 如何在 firebase 中将循环中的 child 添加为 userId

android - 如何为不同的操作系统创建移动应用程序

ios - iOS:如何半速运行模拟器?

firebase - 将集合从云存储导入到 firestore