bibscy
bibscy

Reputation: 2708

Why delegate method is not called?

I am trying to notify ChatViewController that a chat was deleted in MessagesViewController using a protocol, but the delegate method implemented in ChatViewController is never called.
In the navigationController hierarchy ChatViewController is on top of MessagesViewController.

protocol MessagesViewControllerDelegate:class {
  func chatWasDeletedFromDatabase(chatUID: String)
}

class MessagesViewController: UITableViewController {
    weak var delegate: MessagesViewControllerDelegate?

  func observeChatRemoved() {
    print("it is gonna be called")
           //inform ChatViewController that a chat was deleted.
   self.delegate?.chatWasDeletedFromDatabase(chatUID: chat.chatUID)
    print("was called here") //prints as expected
  }
}


  class ChatViewController: JSQMessagesViewController {

     var messagesVC: MessagesViewController? 

    override func viewDidLoad() {
      super.viewDidLoad()

     messagesVC = storyboard?.instantiateViewController(withIdentifier: "MessagesViewController") as! MessagesViewController
     messagesVC?.delegate = self
   }
 }


    extension ChatViewController: MessagesViewControllerDelegate {
    func chatWasDeletedFromDatabase(chatUID: String) {
    print("chatWasDeletedFromDatabase called") //never prints out
      if self.chatSelected.chatUID == chatUID {
         //popToRootViewController
       }

 }

Upvotes: 0

Views: 64

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

It seems

weak var delegate: MessagesViewControllerDelegate?

is nil you have to set it to the ChatViewController presented instance what ever how you present it

let chat = ///
self.delegate = chat
self.navigationController?.pushViewController(chat,animated:true)

Also do

chat.messagesVC = self

as this

 messagesVC = storyboard?.instantiateViewController(withIdentifier: "MessagesViewController") as! MessagesViewController
 messagesVC?.delegate = self

isn't the currently presented messagesVC , so comment the above 2 lines

Upvotes: 1

Related Questions