如何实施Firebase侦听器以观察数据库中的实时变化

时间:2020-01-16 09:03:23

标签: ios swift firebase firebase-realtime-database

我在理解如何实现侦听器时遇到问题,以便可以观察数据库中的更改并将其实时反映到tableview中。我想观察isOnline和isHorizo​​ntal的更改,根据该更改,我将更改标签值以及图像值。这是我的代码:

var userInfoArray : [UserModel] = [UserModel]()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
      // readData()
        tableView.dataSource = self
        tableView.delegate = self
        self.tableView.rowHeight = 70
       retrieveUserInfo()

    }


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//        print(emailModified.count)
        return userInfoArray.count

    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "tableViewCell", for: indexPath) as! TableViewCell
        cell.userLbl.text = "User \([userInfoArray[indexPath.row].email].count)"
        if userInfoArray[indexPath.row].isHorizontal == true {
            cell.messageLbl.text = "I am Horizontal"
        } else {
            cell.messageLbl.text = ""
        }

        if userInfoArray[indexPath.row].isOnline == true {

            cell.onlineImage.image = UIImage(named: "online")
        }else {
            cell.onlineImage.image = UIImage(named: "offline")
        }
        return cell

    }
     func retrieveUserInfo() {
     Database.database().reference().child("new user").observeSingleEvent(of: .value) { (snapshot) in
        for child in snapshot.children.allObjects as! [DataSnapshot] {
            print(child.children)
        // this will iterate through all children in snapshot at at path specified.
            if let userList = child.value as? Dictionary <String,Any> {

                    let email = userList["email"]
                    print(email)
                    let onlineStatus = userList["isOnline"] as! Any
                    let horizontalStatus = userList["isHorizontal"] as! Any

                    let list = UserModel()
                    list.email = email as? String ?? "nil"
                    print(list.email)
                    list.isHorizontal = horizontalStatus  as! Bool
                    list.isOnline = onlineStatus  as!   Bool

                    self.userInfoArray.append(list)
                    print(self.userInfoArray)

            }
            self.tableView.reloadData()
        }
        }

2 个答案:

答案 0 :(得分:0)

.childAdded给您一个接一个的记录。因此请借助完成处理程序将数据取回并将数据放入数组中。

为此的Firebase文档:https://firebase.google.com/docs/database/ios/lists-of-data

示例代码:

func getChatMessages() {
    _firebase.getChatMessages(uniqueId: chatHeadVM.uniqueId) { (messageModel) in
        DispatchQueue.main.async {
            guard let msgModel = messageModel as? MessageModel else {
                return
            }

            self.messageList.append(MessageViewModel(messageInfo: msgModel))
//Reload your table
        }
    }
}

func getChatMessages(uniqueId: String, completionHandlerWithResponseData: @escaping completionHandlerWithResponseData) {
            let query = ref.child(Firebase.chatNodeStr).child(uniqueId)

        query.observe(.childAdded, with: { snapshot in
            if  let dict = snapshot.value as? [String: Any] {
                let messageModel = MessageModel(withDictionary: dict)
                completionHandlerWithResponseData(messageModel)
            }
        }) { (error) in
            print(error.localizedDescription)
            completionHandlerWithResponseData(nil)
        }
    }

希望有帮助。

答案 1 :(得分:0)

我找到了解决方法...

func retrieveUserInfo() {

     Database.database().reference().child("new user").observe(of: 
     DataSnapShot.value) { (snapshot) in
        for child in snapshot.children.allObjects as! [DataSnapshot] {
            print(child.children)
        // this will iterate through all children in snapshot at at path specified.
            if let userList = child.value as? Dictionary <String,Any> {

                    let email = userList["email"]
                    print(email)
                    let onlineStatus = userList["isOnline"] as! Any
                    let horizontalStatus = userList["isHorizontal"] as! Any

                    let list = UserModel()
                    list.email = email as? String ?? "nil"
                    print(list.email)
                    list.isHorizontal = horizontalStatus  as! Bool
                    list.isOnline = onlineStatus  as!   Bool

                    self.userInfoArray.append(list)
                    print(self.userInfoArray)

            }
            self.tableView.reloadData()
        }
        }

我在数据库中发生更改之前先观察一个事件,然后oberver(DataSnapShot.value)通知并观察者。