0

I want to show like count if someone click on like button or dislike. After clicking like button I'm getting the data but, after clicked on like button tableview is not reloading. I had tried but i'm not sure where I'm going wrong. Please can someone help me out.

struct postData {
    let title : String?
    let userId : String?
    var likeCount: Int?
    let likedByUserId : String?
    let likedId : String?
}

class VoicebookViewController: UIViewController,AVAudioPlayerDelegate {
    
    @IBOutlet weak var voicebookTableView: UITableView!
    
    var postArray = [postData]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        voicebookTableView.delegate = self
        voicebookTableView.dataSource = self
        getUsersDataFromFirebase()
    }
 
    @IBAction func likeButtonTapped(_ sender: UIButton)
    {
        
        let obj = postArray[sender.tag]
        if FUser.currentUser()?.userID == obj.likedByUserId ?? ""
        {
           
            let db = FirebaseReference(.Post).document(obj.postId ?? "").collection("Like").document(obj.likedId ?? "")
            db.delete() { err in
                if let err = err {
                    print("Error removing document: \(err)")
                } else {
                    print("Document successfully removed!")
                    DispatchQueue.main.async {
                        
                        self.voicebookTableView.beginUpdates()
                        let indexPath = IndexPath(item: sender.tag, section: 0)
                        self.voicebookTableView.reloadRows(at: [indexPath], with: .automatic)
                        self.voicebookTableView.endUpdates()
                        
                        
                    }
                }
            }
        }
        else
        {
            let refid = FirebaseReference(.Post).document(obj.postId ?? "").collection("Like").document()
            let id = refid.documentID
            let date = Date()
            let formatter = DateFormatter()
            formatter.dateFormat = "dd/MM/YYYY hh:mm:ss a"
            let timeStamp = formatter.string(from: date)
            
            let data = ["likeByUserId":"\(id)","likedToUserId":"\(FUser.currentUser()?.userID ?? "")"] as [String : Any]
            
            refid.setData(data){(error) in
                if let err = error {
                    print("Failed to like recent:", err)
                    return
                }
                else
                {
                    sender.tintColor = UIColor(red: 0.26, green: 0.40, blue: 0.70, alpha: 1.00)
                    sender.setTitleColor(UIColor(red: 0.26, green: 0.40, blue: 0.70, alpha: 1.00), for: .normal)
                    DispatchQueue.main.async {
                        
                        self.voicebookTableView.beginUpdates()
                        let indexPath = IndexPath(item: sender.tag, section: 0)
                        self.voicebookTableView.reloadRows(at: [indexPath], with: .fade)
                        self.voicebookTableView.endUpdates()
                    }
                    
                }
            }
        }
        
    }
    
    func getPostData(name:String,uid:String,img:String)
      {
    self.postArray.removeAll()
    FirebaseReference(.Post).getDocuments{(snapshot, error) in
        if error != nil {
            print("Document Error: ", error!)
        } else {
            if let doc = snapshot, doc.isEmpty == false {
                print("Post Document is present.")
                let desc = doc.documents
                self.postArray.removeAll()
                for item in desc
                {
                    let post = item.data()
                    let puid = item.documentID
                    
                    let title = post["title"] as! String
                    let userId = post["userId"] as! String
                    
                    FirebaseReference(.Post).document(puid).collection("Like").getDocuments{(snapshot1,error) in
                        if error != nil {
                            print("Document Error: ", error!)
                        } else {
                            
                            if let doc1 = snapshot1, doc1.isEmpty == false
                            {
                                let likecount = snapshot1?.count ?? 0
                                let desc1 = doc1.documents
                                
                                var likeByUserId : String?
                                var likeId : String?
                                
                                for item in desc1 {
                                    likeByUserId = item["likedCommentToUserId"] as? String
                                    likeId = item["likeCommentByUserId"] as? String
                                }
                                if userId == uid
                                {
                                    
                                    let object = postData(title: title, userId: userId, likecount: likecount,likedByUserId:likeByUserId, likedId: likeId)
                                    self.postArray.append(object)
                                    self.postArray.sort(by: {$0.date?.compare($1.date!) == .orderedDescending})
                                    
                                    self.voicebookTableView.reloadData()
                                    
                                }
                            }
                            else
                            {
                                print("Like is not present")
                            }
                        }
                    }
                }
            }
        }
    }
}
    
    func getUsersDataFromFirebase()
    {
        FirebaseReference(.Users).getDocuments{(snapshot, error) in
            if error != nil {
                print("Document Error: ", error!)
            } else {
                if let doc = snapshot, doc.isEmpty == false {
                    print("User Document is present.")
                    let desc = doc.documents
                    
                    for item in desc
                    {
                        let user = item.data()
                        
                        let name = user["name"] as! String
                        let uid = user["userID"] as! String
                        let img = user["imgUrl"] as! String
                        self.getPostData(name: name, uid: uid, img: img)
                        
                    }
                }
                else
                {
                    print("User Document is not present.")
                }
            }
        }
    }
}

extension VoicebookViewController: UITableViewDelegate, UITableViewDataSource{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return postArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! VoiceBookTableViewCell
        
        let obj = postArray[indexPath.row]
        cell.NameLabel.text = "\(obj.name ?? "")"

        let pimg = URL(string: obj.img ?? "")
        cell.userImage.sd_setImage(with: pimg, placeholderImage: UIImage(named: "demouser.png"))
        
        if (obj.likecount ?? 0) > 0
        {
            cell.totalLikeButton.isHidden = false
            cell.totalLikedHConstraint.constant = 16
            cell.likedLabel.isHidden = false
            cell.totalLikedLblHConstraint.constant = 16
            cell.likedLabel.text = "\(obj.likecount ?? 0)"
        }
        else
        {
            cell.likedLabel.isHidden = true
            cell.totalLikedLblHConstraint.constant = 0
            cell.totalLikeButton.isHidden = true
            cell.totalLikedHConstraint.constant = 0
        }
        
        if FUser.currentUser()?.userID == obj.likedByUserId ?? ""
        {
            //            4267B2
            self.isLike = false
            cell.likeButton.tintColor = UIColor(red: 0.26, green: 0.40, blue: 0.70, alpha: 1.00)
            cell.likeButton.setTitleColor(UIColor(red: 0.26, green: 0.40, blue: 0.70, alpha: 1.00), for: .normal)
        }
        else
        {
            //            A5ACAC
            cell.likeButton.tintColor = UIColor(red: 0.65, green: 0.67, blue: 0.67, alpha: 1.00)
            cell.likeButton.setTitleColor(UIColor(red: 0.65, green: 0.67, blue: 0.67, alpha: 1.00), for: .normal)
        }
        
        cell.likeButton.tag = indexPath.row
        cell.likeButton.addTarget(self, action: #selector(likeButtonTapped), for: .touchUpInside)
        
        return cell
    }
    
}

Here is my code which I have written. Thank you

  • First of all, why are you calling reloadData() after a beginUpdates()/endUpdates() block? If I understood your code right, it makes no sense – first you reload specific rows and then immediately reload the entire table. Then, regarding your question, did you make sure that rows are not reloaded really? The cellForRowAt should be definitely called if a row is reloaded. Next guess, there might be old data in the row left that is not changed in the cellForRowAt method. You should make sure that you either invalidate all previous data in prepareForReuse() or reload it in cellForRowAt. – lazarevzubov Nov 02 '21 at 06:44
  • And the last guess (which I think is the most realistic) is that you have a threading problem: you call data updates that happen asynchronously and reload UI immediately. So that at the point the UI is reloaded, the data source is not yet updated. I suggest that you make sure that you don't reload cells manually but rather let your data drive updates. That is, you listen for data updates and reload table rows when it's updated. – lazarevzubov Nov 02 '21 at 06:47
  • 2
    Does this answer your question? [Refresh certain row of UITableView based on Int in Swift](https://stackoverflow.com/questions/28206492/refresh-certain-row-of-uitableview-based-on-int-in-swift) – Muhammad Nawaz Nov 02 '21 at 06:50
  • Im using this much code refresh specific row self.voicebookTableView.beginUpdates() let indexPath = IndexPath(item: sender.tag, section: 0) self.voicebookTableView.reloadRows(at: [indexPath], with: .automatic) self.voicebookTableView.endUpdates() – Anand Vishwakarma Nov 02 '21 at 06:51
  • @MuhammadNawaz I have tried that way but not getting result – Anand Vishwakarma Nov 02 '21 at 06:53
  • @AnandVishwakarma dear you have an outlet named postTableView for UITableView and you are using voicebookTableView outlet for refreshing the table row please make sure your outlet is correct – Muhammad Nawaz Nov 02 '21 at 06:57
  • @MuhammadNawaz Okay I have change my outlet name But still I'm not getting the result – Anand Vishwakarma Nov 02 '21 at 07:02
  • That's quite a bit of code for use to parse through and it's not well formatted which makes it hard to follow. Please take a moment and review [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). Also, it would help us for you to do some troubleshooting - there could be SO MANY things causing your issue; add a breakpoint to your code and step through it line by line, checking the vars and processes along they way. When you find one that isn't as expected, update your question and then we can take a look. – Jay Nov 03 '21 at 19:41

0 Answers0