M A M A - 1 year ago 87
Swift Question

Swift: Notifying a ViewController from another using completion handler

I have 2 ViewControllers in my app. One of them named vcA is using a method (here viewDidLoad) to talk to my networking layer (a class in my app). After finishing the networking job (which will be inferred by a completion handler) I want to notify class vcB to call a method to get some data which is provided by networking layer.
Please take a look at below sudo code :

class Networking {

static var PublicValue : SomeKindOfClass? = nil

static func test(completionHandler : (successful : Bool) -> Void) -> Void {
//Do some networking in background
Network.BackgroundNetworking() {
if result = true {
PublicValue = SomeValue
completionHandler(successful : true)
else {
completionHandler(successful : false)

class vcA : UIViewController {

override func viewDidLoad() {

// Do any additional setup after loading the view.
Networking.test(completionHandler : { (successful) in
if successful == true {
//Here I want to notify class vcB to call printPublicValue method

class vcB : UIViewController {

func printPublicValue() {


Answer Source

I agree with @Paulw11 you should consider using NSNotifications. They are easy to set up and use and would work great in this situation. To do this, in one of your view controllers put the following code:

NSNotificationCenter.defaultCenter().postNotificationName("nameOfNotification", object: nil)

In your second view controller (the one that will be receiving the notification) put:

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(NameOfViewController.nameOfFunction(_:)), name: "nameOfNotification", object: nil)

Then you can create a function like so:

func nameOfFunction(notif: NSNotification) {
      //Insert code here

There is a great tutorial here if you want to go more in depth: