Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call view controller method from custom class

Tags:

ios

swift

I have a custom class and a view controller.

My custom class:

class ChatManager:NSObject {

    func messageArrived() {
         //When Message arrives I am handling it from here
         //I need something like that: Viewcontroller.updateTable()
    }
}

When message arrives from internet I need to update tableview in view controller. So I mean I have to call a view controller method from messageArrived method. How can I do this ?

like image 416
Okan Avatar asked Sep 26 '26 04:09

Okan


2 Answers

Here is a simple example of using delegate:

declare the delegate before your chat manager class

protocol ChatManagerDelegate {
    func manageMessage()
}

when the message arrived, call the delegate method to handle it.

class ChatManager: NSObject {

    var delegate: ChatManagerDelegate?

    func messageArrived() {
        self.delegate!.manageMessage()
    }
}

in your view controller, remember to set the delegate of the chat manager to self.

class ViewController: ChatManagerDelegate {
    var manager = ChatManager()
    manager.delegate = self

    func manageMessage() {
        self.updateTable()
    }
}
like image 85
lozy219 Avatar answered Sep 28 '26 20:09

lozy219


This would be a possible implementation:

ViewController:

class ViewController: UIViewController,ChatManagerDelegate {

  override func viewDidLoad() {
    super.viewDidLoad()
    let myChatManager = ChatManager()
      myChatManager.delegate = self
  }


  func messageDidArrive() {
    // Do Things here.
  }
}

Chatmanager:

class ChatManager:NSObject {
  var delegate:ChatManagerDelegate?

  func messageArrived() {
    //When Message arrives I am handling it from here
    //I need something like that: Viewcontroller.updateTable()
  }
}

Delegate-Protocol:

protocol ChatManagerDelegate{
  func messageDidArrive()
}
like image 33
gutenmorgenuhu Avatar answered Sep 28 '26 21:09

gutenmorgenuhu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!