分段控制未如预期那样准确执行

问题描述 投票:-1回答:1

使用表格单元按钮执行操作时,在Firebase中使用分段控件未选择准确的文档。

我在Swift IOS和Firestore数据库中使用带有表视图的分段控件,

我能够按照细分控制要求从数据库加载文档。但是,当我点击表格单元格的按钮时,它仅处理一个文档,而不是准确的文档,我该如何确保表格单元格按钮仅处理与该文档的特定ID相关的文档,下面是代码我正在分享

class IPViewController: UIViewController {

    @IBOutlet var segmentControl:UISegmentedControl!

    @IBOutlet var tableView: UITableView!

    var pendingPost:[Pending] = []
    var completedPost:[Completed] = []

    var postKey:String = ""

       var db: Firestore!


       var postAuthorId:String = ""
       var postAuthorname:String = ""
       var PostTitle:String = ""



    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        tableView.delegate = self
        // Do any additional setup after loading the view.
        retrieveAllPosts()
    }


    func retrieveAllPosts(){
        let postsRef = Firestore.firestore().collection("users").document(Auth.auth().currentUser!.uid).collection("Detaling2").limit(to: 50)

        postsRef.addSnapshotListener { (snapshot, error) in

            if let error = error {

                print(error.localizedDescription)

            } else {

                if let snapshot = snapshot {

                    for document in snapshot.documents {


                        let data = document.data()
                        let username = data["post_author_username"] as? String ?? ""
                        let postTitle = data["postTitle"] as? String ?? ""



                        let newSourse = Pending(_documentId: document.documentID, _username: username, _postTitle: postTitle, _postcategory: postcategory)


                        self.pendingPost.append(newSourse)

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



    func retrieveAllPosts2(){
     let postsRef = Firestore.firestore().collection("users").document(Auth.auth().currentUser!.uid).collection("Detailing1").limit(to: 50)

        postsRef.addSnapshotListener { (snapshot, error) in

            if let error = error {

                print(error.localizedDescription)

            } else {

                if let snapshot = snapshot {

                    for document in snapshot.documents {


                        let data = document.data()
                        //self.postKey = document.documentID
                        let username = data["post_author_username"] as? String ?? ""
                        let postTitle = data["postTitle"] as? String ?? ""



                        let newSourse1 = Completed(_documentId: document.documentID, _username: username, _postTitle: postTitle)


                        self.completedPost.append(newSourse1)

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



    @IBAction func indexChanged(_ sender: UISegmentedControl) {
        switch segmentControl.selectedSegmentIndex
        {
        case 0:
            self.pendingPost.removeAll()

            retrieveAllPosts()
        case 1:
            self.completedPost.removeAll()

            retrieveAllPosts2()
        default:
            break
        }

        //self.tableView.reloadData()
    }

    @objc func toComments(_ sender: AnyObject) {

        let commentbutton = sender as! UIButton
        let post = pendingPost[commentbutton.tag]
        postKey = post._documentId // or what key value it is
        print("hello")
        performSegue(withIdentifier: "IPtoComments", sender: self)

    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        var vc = segue.destination as! CommentListViewController
        vc.postId = postKey

    }
    @objc func favupdate(_ sender: AnyObject) {

           let commentbutton = sender as! UIButton
           let post = pendingPost[commentbutton.tag]
           postKey = post._documentId // or what key value it is
           //print(postKey + "hello777777")

           let userMarkRef = Firestore.firestore().collection("users").document(Auth.auth().currentUser!.uid).collection("marked_posts").document(postKey)
           let postRef = Firestore.firestore().collection("posts").document(postKey)



           postRef.getDocument{(document, error) in
               if let document = document, document.exists{
                   let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
                   self.postAuthorId = document.get("post_author_id") as! String
                   self.postAuthorname = document.get("post_author_username") as! String
                   self.PostTitle = document.get("postTitle") as! String
                   self.postContent = document.get("postContent") as! String
                   self.postAuthorEmail = document.get("post_author_email") as! String
                   self.postCategory = document.get("postcategory") as! String
                   self.postAuthorfullname = document.get("post_author_fullname") as! String
                   self.postAuthorGender = document.get("post_author_gender") as! String
                   self.postAuthorPicUrl = document.get("post_user_profile_pic_url") as! String
                   // let l11:Bool = document.get("l1") as! Bool
                   //  self.postTimeStamp = document.get("post_timeStamp") as! String
                   self.postAuthorSpinnerC = document.get("post_author_spinnerC") as! String

               }

               let postObject = [
                   "post_author_id": self.postAuthorId,
                   "post_author_username": self.postAuthorname,
                   "postTitle": self.PostTitle

                   ] as [String : Any]



               userMarkRef.setData(postObject, merge: true) { (err) in
                   if let err = err {
                       print(err.localizedDescription)
                   }
                   print("Successfully set new user data")
               }

           }



       }


    @objc func favupdate1(_ sender: AnyObject) {

         let commentbutton = sender as! UIButton
         let post = completedPost[commentbutton.tag]
         postKey = post._documentId 
         let userMarkRef = Firestore.firestore().collection("users").document(Auth.auth().currentUser!.uid).collection("details1").document(postKey)
         let postRef = Firestore.firestore().collection("posts").document(postKey)



         postRef.getDocument{(document, error) in
             if let document = document, document.exists{
                 let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
                 self.postAuthorId = document.get("post_author_id") as! String
                 self.postAuthorname = document.get("post_author_username") as! String
                 self.PostTitle = document.get("postTitle") as! String

             }

             let postObject = [
                 "post_author_id": self.postAuthorId,
                 "post_author_username": self.postAuthorname,
                 "postTitle": self.PostTitle
                 ] as [String : Any]



             userMarkRef.setData(postObject, merge: true) { (err) in
                 if let err = err {
                     print(err.localizedDescription)
                 }
                 print("Successfully set new user data")
             }

         }



     }



}


extension IPViewController: UITableViewDelegate, UITableViewDataSource{

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var value = 0
        switch segmentControl.selectedSegmentIndex{
        case 0:
            value = pendingPost.count
            break
        case 1:
            value = completedPost.count
            break
        default:
            break
        }
        return value
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ipwcell", for: indexPath) as! IPWCELL
        switch segmentControl.selectedSegmentIndex{
        case 0:

            cell.pending1 = pendingPost[indexPath.row]
            cell.commentbuttonIp.tag = indexPath.row
            cell.commentbuttonIp.addTarget(self, action: #selector(toComments(_:)), for: .touchUpInside)
            cell.favoritebutton1.addTarget(self, action: #selector(favupdate(_:)), for: .touchUpInside)


            break
        case 1:

            cell.completed1 = completedPost[indexPath.row]
            cell.commentbuttonIp.tag = indexPath.row
            cell.commentbuttonIp.addTarget(self, action: #selector(toComments(_:)), for: .touchUpInside)
            cell.favoritebutton1.addTarget(self, action: #selector(favupdate1(_:)), for: .touchUpInside)


            break

        default:
            break
        }
        return cell
    }





}
ios swift uitableview google-cloud-firestore uisegmentedcontrol
1个回答
1
投票
   @objc func favupdate(_ sender: AnyObject) {


     if segmentView.selectedSegmentIndex == 0 {
        let commentbutton = sender as! UIButton
                    let post = pendingPost[commentbutton.tag]
                    postKey = post._documentId // or what key value it is
                    //print(postKey + "hello777777")

                    let userMarkRef = Firestore.firestore().collection("users").document(Auth.auth().currentUser!.uid).collection("marked_posts").document(postKey)
                    let postRef = Firestore.firestore().collection("posts").document(postKey)



                    postRef.getDocument{(document, error) in
                        if let document = document, document.exists{
                            let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
                            self.postAuthorId = document.get("post_author_id") as! String
                            self.postAuthorname = document.get("post_author_username") as! String
                            self.PostTitle = document.get("postTitle") as! String
                            self.postContent = document.get("postContent") as! String
                            self.postAuthorEmail = document.get("post_author_email") as! String
                            self.postCategory = document.get("postcategory") as! String
                            self.postAuthorfullname = document.get("post_author_fullname") as! String
                            self.postAuthorGender = document.get("post_author_gender") as! String
                            self.postAuthorPicUrl = document.get("post_user_profile_pic_url") as! String
                            // let l11:Bool = document.get("l1") as! Bool
                            //  self.postTimeStamp = document.get("post_timeStamp") as! String
                            self.postAuthorSpinnerC = document.get("post_author_spinnerC") as! String

                        }

                        let postObject = [
                            "post_author_id": self.postAuthorId,
                            "post_author_username": self.postAuthorname,
                            "postTitle": self.PostTitle

                            ] as [String : Any]



                        userMarkRef.setData(postObject, merge: true) { (err) in
                            if let err = err {
                                print(err.localizedDescription)
                            }
                            print("Successfully set new user data")
                        }

                    }


     }else {
        let commentbutton = sender as! UIButton
        let post = completedPost[commentbutton.tag]
        postKey = post._documentId
        let userMarkRef = Firestore.firestore().collection("users").document(Auth.auth().currentUser!.uid).collection("details1").document(postKey)
        let postRef = Firestore.firestore().collection("posts").document(postKey)



        postRef.getDocument{(document, error) in
            if let document = document, document.exists{
                let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
                self.postAuthorId = document.get("post_author_id") as! String
                self.postAuthorname = document.get("post_author_username") as! String
                self.PostTitle = document.get("postTitle") as! String

            }

            let postObject = [
                "post_author_id": self.postAuthorId,
                "post_author_username": self.postAuthorname,
                "postTitle": self.PostTitle
                ] as [String : Any]



            userMarkRef.setData(postObject, merge: true) { (err) in
                if let err = err {
                    print(err.localizedDescription)
                }
                print("Successfully set new user data")
            }

        }
    }

   }

  @objc func toComments(_ sender: AnyObject) {


    if segmentView.selectedSegmentIndex == 0 {
        let commentbutton = sender as! UIButton
               let post = pendingPost[commentbutton.tag]
               postKey = post._documentId // or what key value it is
               print("hello")
               performSegue(withIdentifier: "IPtoComments", sender: self)
    }else {
        let commentbutton = sender as! UIButton
               let post = pendingPost[commentbutton.tag]
               postKey = post._documentId // or what key value it is
               print("hello")
               performSegue(withIdentifier: "IPtoComments", sender: self)
    }


}
© www.soinside.com 2019 - 2024. All rights reserved.