Swift iOS Pearls: Broadcasting Messages

Hi people, I started working full time with iOS development using Swift recently and I want to follow the same series as Android Pearls but showing you things that were helpful for me in a certain moment to accomplish something in particular.

As an Android developer I commonly use the Broadcast messages using the helper class LocalBroadcastManager to send messages between decoupled objects like Activities and Services, those runs in different threads so broadcasting a message is the best way to communicate between them.

So, how do We do that in iOS, specifically with Swift…

Sending the Message

In order to send the message We will be using the helper class NotificationCenter, We will get the default instance of that class and then use the method post that will send the message as follows:

let anyDataToSend = ["full_name" : "John Doe"]

NotificationCenter.default.post(name: Notification.Name(rawValue: "notification_key"),object: self, userInfo: anyDataToSend)

In that example We are sending a notification with the key notification_key, and also passing a parameter or userInfoto it.

Receiving the Message

To get the messages for that specific key we will need to subscribe to the NotificationCenter, specifying the key. First we will need to override the viewWillAppear function in our ViewController as follows:

override func viewWillAppear(_ animated: Bool) { }

Inside the method we place the subscription to the notifications of a certain key and we specify a selector to have a function to handle when the message is received, check the example:

NotificationCenter.default.addObserver(self, selector: #selector(handleNotification(withNotification:)), name: NSNotification.Name(rawValue:"notification_key"), object: nil)

We declare the handleNotificationmethod as follows:

func handleNotification(withNotification notification : NSNotification) { }

And to get the data we previously sent we do it like this:

notification.userInfo?[“full_name”]

You can add as many values as you want to the dictionary posted with the notifications, this is pretty easy and straightforward to implement.

I hope this article helped you.