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

如何从Firebase查询数据填充textField,修改后更新对应数据库条目

解决方案

你现有代码存在两个核心问题:

  1. 读取数据时调用db.collection("utenti").document()没有传入目标文档ID,这里生成的是新的空文档引用,无法读取到已有用户数据
  2. getDocument是异步接口,不能直接同步获取返回值,需要在回调中处理读取结果

1. 兼容现有数据库结构的实现

读取nome字段赋值给输入框
let db = Firestore.firestore()
// 安全校验用户登录状态
guard let userID = Auth.auth().currentUser?.uid else {
    // 此处补充用户未登录的处理逻辑
    return
}
// 按用户uid查询对应用户文档
db.collection("utenti").whereField("uid", isEqualTo: userID).getDocuments { snapshot, error in
    if let error = error {
        print("用户数据读取失败: \(error.localizedDescription)")
        return
    }
    guard let userDoc = snapshot?.documents.first else {
        print("未匹配到对应用户数据")
        return
    }
    // 读取nome字段并赋值给输入框
    if let nome = userDoc.get("nome") as? String {
        // 直接赋值到输入框内容
        self.nomeTextField.text = nome
        // 若仅需要修改占位符则替换为下面的代码
        // self.nomeTextField.placeholder = nome
    }
}
修改后点击按钮更新数据库
@IBAction func updateUserInfo(_ sender: UIButton) {
    guard let userID = Auth.auth().currentUser?.uid,
          let newNome = nomeTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines),
          !newNome.isEmpty else {
        mostraErrore("姓名不能为空")
        return
    }
    let db = Firestore.firestore()
    // 查询对应用户文档
    db.collection("utenti").whereField("uid", isEqualTo: userID).getDocuments { snapshot, error in
        if let error = error {
            self.mostraErrore(error.localizedDescription)
            return
        }
        guard let docID = snapshot?.documents.first?.documentID else {
            self.mostraErrore("未找到用户数据")
            return
        }
        // 更新nome字段
        db.collection("utenti").document(docID).updateData(["nome": newNome]) { error in
            if let error = error {
                self.mostraErrore("更新失败: \(error.localizedDescription)")
            } else {
                // 此处可补充更新成功的提示逻辑
                print("姓名更新成功")
            }
        }
    }
}

2. 优化方案(推荐)

你当前注册时用addDocument生成随机文档ID,每次读写都需要先查询,效率更低,建议注册时直接用用户uid作为文档ID,后续读写会简化很多。
仅需要修改注册时的写入代码:
把原来的addDocument逻辑替换为setData,指定文档ID为用户uid:

// 原来的db.collection("utenti").addDocument(...) 替换为下面的代码
db.collection("utenti").document(authResult!.user.uid).setData(["nome":nome, "cognome":cognome, "email": email, "uid": authResult!.user.uid]) { (erroreNome_Cognome) in
    if erroreNome_Cognome != nil {
        self.mostraErrore("用户数据写入数据库失败")
    }
}

修改之后读取数据的代码可以简化为:

db.collection("utenti").document(userID).getDocument { snapshot, error in
    if let snapshot = snapshot, snapshot.exists, let nome = snapshot.get("nome") as? String {
        self.nomeTextField.text = nome
    }
}

更新数据的代码也不需要提前查询,直接用uid获取文档引用更新即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 11:45:04