Firebase中的更改不会刷新表-表未显示数组中的用户节点 [英] Change in firebase doesn't refresh table - Tables not displaying user nodes from arrays

查看:97
本文介绍了Firebase中的更改不会刷新表-表未显示数组中的用户节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图拥有两个数组,用作两个tableViews的数据源.一个数组包含用户类型:宏,另一个数组包含用户类型:micro.

I am trying to have two arrays, used as dataSources for two tableViews. One array contains user type: macro and the other array contains user type: micro.

如果用户类型从宏更改为微型(反之亦然),我想从一个表中删除该用户并将其添加到另一个表中.

If a user type is changed from macro to micro (and vice-versa) I want to remove the user from one table and add it to the other.

当前,如果能够在Firebase数据库中进行更改,则我可以更新用户的标签,并在重新启动应用程序时将其显示在正确的数组中.观察函数仅收集一次,如果它被更改,它不会更新该表,直到用户退出该应用程序并重新打开它为止.除非它们执行了前面提到的操作,否则我正在观察的功能.childChanged似乎不会立即在用户的应用程序上更新数组.

Currently I am able to update the user's tag if changed in Firebase Database and have it appear in the proper array when the app is restarted. The observe function only collects it once and if it is changed, it doesn't update the table until the user quits the app and reopens it. The function I am using to observe.childChanged doesn't seem to update the arrays immediately on the user's app unless they do what was mentioned previously.

我的主要问题是我的表没有显示该表的用户.我可以访问他们的节点和用户,但是它们没有出现在我的表中.

My main problem is that my tables are not displaying the users to the table. I am able to access their node and user but they are not appearing in my tables.

这是我的用户类的代码:

Here is the code for my user class:

import UIKit
import Firebase

    class User: NSObject {
        var Name: String?
        var Email: String?
        var UID: String?
        var Tag: String?

init?(from snapshot: DataSnapshot) {

        let dictionary = snapshot.value as? [String: Any]
    
        self.Name = dictionary!["Name"] as? String
        self.Email = dictionary!["Email"] as? String
        self.UID = dictionary!["UID"] as? String
        self.Tag = dictionary!["Tag"] as? String
        
        }
}

这是我的代码,用于加载和填充信息附加的allUsersArray:

Here is my code for loading and populating my allUsersArray the info appends:

func loadAllUsersAndPopulateArray() {
    let ref = Database.database().reference().child("Users")
    ref.observeSingleEvent(of: .value, with: { snapshot in
        let allUsersSnapshot = snapshot.children.allObjects as! [DataSnapshot]
        for userSnap in allUsersSnapshot {
            let user = User(from: userSnap)
            self.allUsersArray.append(user!)
            
            self.macroUsersArray = self.allUsersArray.filter { $0.Tag == "Macro" }
            self.microUsersArray = self.allUsersArray.filter { $0.Tag == "Micro" }

            self.observeChangeInUserProperty()
        }
    })
}

这是我的代码,用于观察Firebase的更改:

Here is my code for observing the change from Firebase:

 func observeChangeInUserProperty() {
    let ref = Database.database().reference().child("Users")
    ref.observe(.childChanged, with: { snapshot in
        let key = snapshot.key

        let tag = snapshot.childSnapshot(forPath: "Tag").value as! String // ! = never optional
        //get the user from the allUsersArray by its key
        if let user = self.allUsersArray.first(where: { $0.Tag == key }) {
            if user.Tag != tag { //if the tag changed, handle it
                user.Tag = tag //update the allUsersArray
                if tag == "Macro" { //if the new tag is Macro remove the user from the Micro array
                    if let userIndex = self.microUsersArray.firstIndex(where: { $0.Tag == key }) {
                        self.microUsersArray.remove(at: userIndex)
                        self.macroUsersArray.append(user) //add user to macro array
                    }
                } else { //new type is micro so remove from macro array
                    if let userIndex = self.macroUsersArray.firstIndex(where: { $0.Tag == key }) {
                        self.macroUsersArray.remove(at: userIndex)
                        self.microUsersArray.append(user)
                    }
                }
                //reload the tableviews to reflect the changes
                self.tableView.reloadData()
                self.microTableView.reloadData()

            }
        }
    })
}

这是我的控制器代码:

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var allUsersArray = [User]()
var macroUsersArray = [User]()
var microUsersArray = [User]()

override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.delegate = self
        tableView.dataSource = self
        searchBar.delegate = self
        tableView.register(UserCell.self, forCellReuseIdentifier: networkCell)
        
        microTableView.delegate = self
        microTableView.dataSource = self
        microTableView.register(microCell.self, forCellReuseIdentifier: microCell)
        
        loadAllUsersAndPopulateArray()
        
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        if (tableView === self.tableView) {
        
            return 1
            
          }


        else if (tableView === self.microTableView) {
            // Do something else
        
            return 1
        
        }
        
        fatalError("Invalid table")
        
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if (tableView === self.tableView) {
            
                let cell = tableView.dequeueReusableCell(withIdentifier: networkCell, for: indexPath) as! UserCell
            
                let user = macroUsersArray[indexPath.row]
                cell.textLabel?.text = user.Name
                    
                    return cell
                    
                } else if (tableView === self.microTableView) {
                    
                    let cell = tableView.dequeueReusableCell(withIdentifier: microCell, for: indexPath) as! microInfluencerCell
                
                    let user = microUsersArray[indexPath.row]
                    cell.textLabel?.text = user.Name
                
                        return cell
            
        } else {
            fatalError("Invalid table")
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if (tableView === self.tableView) {
            return macroUsersArray.count
        }
        else if (tableView === self.microTableView) {
            return microUsersArray.count
        }
        
        else {
            fatalError("Invalid table")
        }

    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if (tableView === self.tableView) {
            return 72
        }
        else if (tableView === self.microTableView) {
            return 72
        }
        
        else {
            fatalError("Invalid table")
        }
    }

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
    if (tableView === self.tableView) {
        
        dismiss(animated: true) {
            let userName = self.macroUsersArray[indexPath.row]
            self.showSecondViewController(user: userName)

            print("Dismiss completed")
        }
        
    }
    else if (tableView === self.microTableView) {
        
        dismiss(animated: true) {
            let userName = self.microUsersArray[indexPath.row]
            self.showSecondController(user: userName)

            print("Dismiss completed")
        }
        
    }
    
    else {
        fatalError("Invalid table")
    }
  }
}

func showSecondViewController(user: User) {

    let SecondViewController = SecondViewController()
    SecondViewController.user = user
    let navigationController = UINavigationController(rootViewController: SecondViewController)
    self.present(navigationController, animated: true, completion: nil)
  }

func loadAllUsersAndPopulateArray() {
let ref = Database.database().reference().child("Users")
ref.observeSingleEvent(of: .value, with: { snapshot in
    let allUsersSnapshot = snapshot.children.allObjects as! [DataSnapshot]
    for userSnap in allUsersSnapshot {
        let user = User(from: userSnap)
        self.allUsersArray.append(user!)

        self.macroUsersArray = self.allUsersArray.filter { $0.Tag == "Macro" }
        self.microUsersArray = self.allUsersArray.filter { $0.Tag == "Micro" }

        self.observeChangeInUserProperty()
     }
   })
 }
func observeChangeInUserProperty() {
let ref = Database.database().reference().child("Users")
ref.observe(.childChanged, with: { snapshot in
    let key = snapshot.key

    let tag = snapshot.childSnapshot(forPath: "Tag").value as! String // ! = never optional
    //get the user from the allUsersArray by its key
    if let user = self.allUsersArray.first(where: { $0.Tag == key }) {
        if user.Tag != tag { //if the tag changed, handle it
            user.Tag = tag //update the allUsersArray
            if tag == "Macro" { //if the new tag is Macro remove the user from the Micro array
                if let userIndex = self.microUsersArray.firstIndex(where: { $0.Tag == key }) {
                    self.microUsersArray.remove(at: userIndex)
                    self.macroUsersArray.append(user) //add user to macro array
                }
            } else { //new type is micro so remove from macro array
                if let userIndex = self.macroUsersArray.firstIndex(where: { $0.Tag == key }) {
                    self.macroUsersArray.remove(at: userIndex)
                    self.microUsersArray.append(user)
                }
            }
            //reload the tableviews to reflect the changes
            self.tableView.reloadData()
            self.microTableView.reloadData()

        }
       }
    })
  }
}

我已经很接近解决这个问题了.任何帮助都将是惊人的.

I am so close to getting this problem solved. Any help would be amazing.

func loadAllUsersAndPopulateArray() {
    let ref = Database.database().reference().child("Users").child("Talent")
    ref.observeSingleEvent(of: .value, with: { snapshot in
        let allUsersSnapshot = snapshot.children.allObjects as! [DataSnapshot]
        for userSnap in allUsersSnapshot {
            let user = User(from: userSnap)
            self.allUsersArray.append(user!)
            self.allUsersNames.append(user!.Name!)

        }

        self.observeChangeInUserProperty()
    })

    self.macroUsersArray = self.allUsersArray.filter { $0.Tag == "Macro" }
    self.microUsersArray = self.allUsersArray.filter { $0.Tag == "Micro" }
    
    self.tableView.reloadData()
    self.microTableView.reloadData()
    
}

推荐答案

在Jay的帮助下,我找到了解决方案!

With the help from Jay I was able to figure out the solution!

我需要在闭包内部设置数组信息.每当有人的标签更新时,都需要关闭并重新打开该应用程序以显示在Firebase中所做的新更改.

I needed to be setting my arrays info from within the closure. Whenever a person's tag is updated, the app needs to be closed and reopened to show the new change made in firebase.

感谢@Jay的所有帮助!

Thank you @Jay for all the help!!!

这是新的功能代码:

func loadAllUsersAndPopulateArray() {
    let ref = Database.database().reference().child("Users")
    ref.observeSingleEvent(of: .value, with: { snapshot in
        let allUsersSnapshot = snapshot.children.allObjects as! [DataSnapshot]
        for userSnap in allUsersSnapshot {
            let user = User(from: userSnap)
            self.allUsersArray.append(user!)
            self.allUsersNames.append(user!.Name!)

            self.macroUsersArray = self.allUsersArray.filter { $0.Tag == "Macro" }
            self.microUsersArray = self.allUsersArray.filter { $0.Tag == "Micro" }

            self.tableView.reloadData()
            self.microTableView.reloadData()
            
        }

        self.observeChangeInUserProperty()
    })
    

这篇关于Firebase中的更改不会刷新表-表未显示数组中的用户节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆