【问题标题】:I want my tableview to reload after it sees a change in firestore database我希望我的 tableview 在看到 firestore 数据库发生变化后重新加载
【发布时间】:2020-07-28 02:27:38
【问题描述】:

** 我希望我的 tableview 在看到 firestore 数据库发生变化后重新加载函数加载后要重新加载的数据每天的动机发生了变化**

    import UIKit
    import Firebase

   //MARK: MAINVIEW MOTIVATION

    class motivationviewcontroller : UIViewController,UITableViewDataSource,UITableViewDelegate{


var motivationThoughts = [MotivatioNDataModel]()

var tableview : UITableView!

override func viewDidLoad() {
    print("madicc")

    print("the user logged in is \( Auth.auth().currentUser?.email)")

    tableview =  UITableView(frame: view.bounds, style: .plain)
           tableview.backgroundColor = UIColor.white
           view.addSubview(tableview)


    var layoutGuide : UILayoutGuide!
    layoutGuide = view.safeAreaLayoutGuide

    let cellNib = UINib(nibName: "dailyMotivationTableViewCell", bundle: nil)
    tableview.register(cellNib, forCellReuseIdentifier: "DailyThoughtCELL")



    tableview.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true
    tableview.topAnchor.constraint(equalTo: layoutGuide.topAnchor).isActive = true
    tableview.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor).isActive = true
    tableview.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor).isActive = true


    tableview.dataSource = self
    tableview.delegate = self


    loaddailymotivation()
    self.tableview.reloadData()


}

override func viewDidAppear(_ animated: Bool) {


  //loaddailymotivation()
    self.tableview.reloadData()

}



    //======================================================================

  //MARK: LOADS THE DATA INTO THE TABLEVIEW
   func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    motivationThoughts.count
   }

   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "DailyThoughtCELL", for: indexPath) as? dailyMotivationTableViewCell

    cell!.generateCellsforDailymotivation(_MotivationdataMODEL: motivationThoughts[indexPath.row])

    return cell!
   }





//MARK: FUNCTION THAT HANDLES GETTING THE DATA FROM FIREBASE
func loaddailymotivation() {

    FirebaseReferece(.MotivationDAILY).getDocuments { (snapshot, error) in

        if let error = error {
            print("error getting MOTIVATIONDAILY DATA \(error.localizedDescription)")
        }

        else {

            guard let snapshot = snapshot else { return }

        for allDocument in snapshot.documents {

                let data = allDocument.data()


                print("\(allDocument.documentID) => \(allDocument.data())")

                print("we have\(snapshot.documents.count) documents in this array")

                let dailymotivationTitle = data["Motivation title"] as! String //calls the data thats heald inside of motivation title in firebase
                let dailyMotivationScripture = data["daily motivation scripture"] as! String //calls the data thats heald inside of Motivation script in firebase

                let dailyMotivationNumberOfLikes = data["Number of likes in daily motivation post"]as! Int


            let newthought = MotivatioNDataModel(RealmotivationTitle: dailymotivationTitle, RealmotivationScrip: dailyMotivationScripture, RealmotivationNumberOfLikes: dailyMotivationNumberOfLikes )
            self.motivationThoughts.append(newthought)


              }
        }


    }


}

【问题讨论】:

    标签: swift xcode firebase google-cloud-firestore


    【解决方案1】:

    问题是你正在获取数据但之后没有重新加载你的 tableView,用下面的改变你的 loaddailymotivation()

    func loaddailymotivation() {
            FirebaseReferece(.MotivationDAILY)
            .addSnapshotListener { querySnapshot, error in
                guard let snapshot = querySnapshot else {
                    print("Error fetching snapshots: \(error!)")
                    return
                }
                snapshot.documentChanges.forEach { diff in
                    if (diff.type == .added) {
    
                        let data = diff.document.data()
    
                        let dailymotivationTitle = data["Motivation title"] as! String //calls the data thats heald inside of motivation title in firebase
                        let dailyMotivationScripture = data["daily motivation scripture"] as! String //calls the data thats heald inside of Motivation script in firebase
    
                        let dailyMotivationNumberOfLikes = data["Number of likes in daily motivation post"]as! Int
    
    
                        let newthought = MotivatioNDataModel(RealmotivationTitle: dailymotivationTitle, RealmotivationScrip: dailyMotivationScripture, RealmotivationNumberOfLikes: dailyMotivationNumberOfLikes )
                        self.motivationThoughts.append(newthought)
    
                    }
                    if (diff.type == .modified) {
                        print("Modified data: \(diff.document.data())")
                        //  here you will receive if any change happens in your data add it to your array as you want
                    }
    
                    DispatchQueue.main.async {
                        self.tableview.reloadData()
                    }
    
                }
            }
        }
    

    在这里,我已将侦听器添加到您的 Firestore 数据中,因此如果有任何新数据添加或任何数据更改到数据库中,您将在应用程序中收到它并实时反映该更改。

    按照我在代码中的注释做一件事。

    【讨论】:

    • 所以当我单击like 按钮时我有一个like 按钮,我希望更改显示在tableview 单元格中,我应该把它放在哪里?在这个
    • 以上代码中的“修改”如果正文中您将收到更改后的数据集,请在此处编写代码
    【解决方案2】:

    您可以尝试将“addSnapshotListener”添加到您的“处理从 FIREBASE 获取数据的函数”中。

    让我们尝试像这样添加它:

    func loaddailymotivation() {
    
    FirebaseReferece(.MotivationDAILY).getDocuments.addSnapshotListener { (snapshot, error) in
    
        if let error = error {
            print("error getting MOTIVATIONDAILY DATA \(error.localizedDescription)")
        }
    
        else {
    
            guard let snapshot = snapshot else { return }
    
        for allDocument in snapshot.documents {
    
                let data = allDocument.data()
    
    
                print("\(allDocument.documentID) => \(allDocument.data())")
    
                print("we have\(snapshot.documents.count) documents in this array")
    
                let dailymotivationTitle = data["Motivation title"] as! String //calls the data thats heald inside of motivation title in firebase
                let dailyMotivationScripture = data["daily motivation scripture"] as! String //calls the data thats heald inside of Motivation script in firebase
    
                let dailyMotivationNumberOfLikes = data["Number of likes in daily motivation post"]as! Int
    
    
            let newthought = MotivatioNDataModel(RealmotivationTitle: dailymotivationTitle, RealmotivationScrip: dailyMotivationScripture, RealmotivationNumberOfLikes: dailyMotivationNumberOfLikes )
            self.motivationThoughts.append(newthought)
    
    
              }
        }
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-08
      • 1970-01-01
      • 1970-01-01
      • 2020-04-08
      • 1970-01-01
      • 2015-04-06
      • 2013-06-21
      • 2011-06-11
      相关资源
      最近更新 更多