【问题标题】:adding a child to a child in Firebase Database with Swift使用 Swift 在 Firebase 数据库中添加一个孩子
【发布时间】:2017-08-30 02:53:27
【问题描述】:

我正在使用以下 Firebase 数据库:

我使用以下代码添加新的聊天 ID:

DatabaseReference.users(uid: self.uid).reference().child("chatIds/\(chat.uid)").setValue(chat.uid)

我需要向个人 "chatIDs" 添加一个孩子,这是我将生成的随机字符串,但我没有使用 Firebase 这么长时间,所以我不确定如何添加孩子这么远。我该如何编写代码来做到这一点?

【问题讨论】:

  • 那有什么问题呢?你已经回答过了
  • 您想在不设置值的情况下添加孩子吗?或者你的问题是什么?

标签: ios swift firebase firebase-realtime-database


【解决方案1】:

根据您的数据库结构,您想要的可能实现是:

let ref = Database.database().reference()

// Generating the chat id
let refChats = ref.child("chats")
let refChat = refChats.childByAutoId()

// Accessing the "chatIds branch" from a user based on
// his id 
let currentUserId = self.uid
let refUsers = ref.child("users")
let refUser = refUsers.child(currentUserId)
let refUserChatIds = refUser.child("chatIds")

// Setting the new Chat Id key created before
// on the "chatIds branch"
let chatIdKey = refChat.key
let refUserChatId = refUserChatIds.child(chatIdKey)
refUserChatIds.setValue(chatIdKey)

【讨论】:

  • 好的。我想我现在看到了。我会尽快尝试的。谢谢
【解决方案2】:

我想你要找的是这个

    let key = firebaseRef.child("users").child("\(String(describing: uid))").child("chatIds").childByAutoId().key

    let timestamp = Int(Date().timeIntervalSince1970)

    let child = ["key":key,
                 "name": name as String,
                 "date": birth as String,
                 "created": "\(timestamp)"]

    firebaseRef.child("users").child("\(String(describing: uid!))").child("chatIds").child(key).setValue(child)

作为示例,我将密钥、名称、日期和创建,作为chatIds 的子项,使用childByAutoId 生成随机密钥,以便您在搜索对象时找到它。

【讨论】:

    【解决方案3】:
        import UIKit
        import Firebase
    
        class ChatListVC: UIViewController {
                var ref: FIRDatabaseReference!
                var messages: [FIRDataSnapshot]! = []
                fileprivate var _refHandle: FIRDatabaseHandle?
    override func viewDidLoad() {
            super.viewDidLoad()
    self.userDetail()
    }
            func userDetail(){
            _refHandle = self.ref.child("users").child("child id").observe(.value, with: { [weak self] (snapshot) -> Void in
                        guard let strongSelf = self else { return }
                        guard let dict = snapshot.value as? [String:Any] else { return }
            //access data from dict
    
            let MyName = dict["MyName"] as? String ?? ""
             })
        }
    

    【讨论】:

      猜你喜欢
      • 2019-06-24
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 2017-02-22
      • 2023-03-20
      • 1970-01-01
      • 2017-05-27
      • 1970-01-01
      相关资源
      最近更新 更多