skip to Main Content

I have a tableview which shows a custom cell.
Inside the cell is a button.

Once the button is clicked, a network call is made and the tableview should reload.

I tried this, but I get Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value at vc.reloadData().

  @IBAction func acceptRequestPressed(_ sender: UIButton) {
       
        DatabaseManager.shared.AnswerFriendRequest(emailFriend: friendNameLabel.text!, answer: true) { success in
            if success {
                
                let vc = FriendRequestViewController()
                vc.reloadData()
                
            }else {
                print ("error at answer")
            }
        }
    }

2

Answers


  1. The problem is this line:

    let vc = FriendRequestViewController()
    

    After that, vc is the wrong view controller — it is just some view controller living off emptily in thoughtspace, whereas the view controller you want is the already existing view controller that’s already in the view controller hierarchy (the "interface").

    Login or Signup to reply.
  2. Few pointers:

    1. You can have a closure upon the data call completion in your class that has the table view.
      Eg:

      // Custom Table Cell Class
      class CustomCellClass: UITableViewCell {

       let button = UIButton()
       // All other UI set up
      
       // Create a closure that your tableView class can use to set the logic for reloading the tableView
       public let buttonCompletion: () -> ()
      
       @IBAction func acceptRequestPressed(_ sender: UIButton) {
      
           DatabaseManager.shared.AnswerFriendRequest(emailFriend: friendNameLabel.text!, answer: true) { [weak self] success in
               if success {
                   // Whatever logic is provided in cellForRow will be executed here. That is, tableView.reloadData() 
                   self?.buttonCompletion() 
      
               }else {
                   print ("error at answer")
               }
           }
       }
      

      }

    // Class that has tableView:

    class SomeViewController: UIViewController {
    
        private let tableView = UITableView()
        .
        .
        // All other set up, delegate, data source
        
        func cellForRow(..) {
           let cell = tableView.dequeueTableViewCell(for: "Cell") as! CustomCellClass
        
            cell.buttonCompletion = {[weak self] in
                tableView.reloadData()
           }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search