You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS Swift中Firebase Realtime Database与Firestore的push()等效方法是什么?

Firebase 自动生成子位置引用的Swift实现

Realtime Database 端

Android中push()方法的Swift等效API为childByAutoId(),二者生成的唯一ID规则完全一致,都基于时间戳排序:

import FirebaseDatabase

// 示例:在posts节点下生成自动ID的子节点引用
let dbRef = Database.database().reference()
let autoGeneratedRef = dbRef.child("posts").childByAutoId()

// 直接通过该引用写入数据
autoGeneratedRef.setValue([
    "title": "测试内容",
    "uid": "当前用户ID"
])

你可以通过autoGeneratedRef.key拿到生成的自动ID字符串。

Firestore 端

Firestore中自动生成文档ID的方式有两种,可按需选择:

方式1:先获取引用再写入

调用无参数的document()方法即可生成带自动ID的文档引用,和Android端collection.document()等效:

import FirebaseFirestore

let firestore = Firestore.firestore()
let autoDocRef = firestore.collection("posts").document()

// 写入数据
autoDocRef.setData([
    "title": "测试内容",
    "uid": "当前用户ID"
])

方式2:直接写入自动ID文档

如果不需要提前拿到引用,可直接调用addDocument方法:

firestore.collection("posts").addDocument(data: [
    "title": "测试内容",
    "uid": "当前用户ID"
]) { error in
    if let error = error {
        print("数据写入失败:\(error.localizedDescription)")
        return
    }
    print("自动ID文档写入完成")
}

内容的提问来源于stack exchange,提问作者learner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 04:06:04