NSNotification/NSNotificationCenter or NotificationCenter in Swift

How to use NSNotification/NSNotificationCenter or NotificationCenter in Swift3 in  your iOS app

Introduction to NSNotification/NSNotificationCenter/ NotificationCenter :

Notification are good source when some one wants to trigger an action upon certain events happening during iOS app development. This thing can be achieved using NotificationCenter as it works like one to may relation using observers in comparison with delegates where we only have one to one relation between objects.  
With the introduction swift3 lots of syntax changes happened. In this post we will learn about how to implement NotificationCenter in iOS using swift3.

Implementation of code : 

 In swift3 NSNOtificationCenter class is no longer available and is replaced with NotificationCenter
First add notification observer  to the class where we want to get notified of certain event like if user went offline and did not connected to internet then show him message about No internet connection.

Adding Notification observer

   NotificationCenter.default.addObserver(self, selector: #selector(moveSegmentYPosition), name: Notification.Name(“NO_INTERNET_CONNECTIVITY”), object: nil)

 In above code we did following things 
1) added observer using addObserver() method of NotificationCenter, it takes three parameters 
  • observer: the class you want to get notified when notification gets fired up (in out=r case when user went offline) 
  • selector: method name you want to get called 
  • name: name of the notification, in swift it take parameter of type Notification class. 
  • object: object whose notifications the observer wants to receive; that is, only notifications sent by this sender are delivered to the observer
2) set name of our notification, in our case it’s “NO_INTERNET_CONNECTIVITY”

Defining our method

    func showInterentMessage() {

        // this will gets called when ever out no interenet

 Posting Notification

 At this moment we are done with adding our notification center and now we have to trigger/fire it when internet went off. You can post notification or fire the notification using below code
    NotificationCenter.default.post(name: Notification.Name(“NO_INTERNET_CONNECTIVITY”), object: nil, userInfo: nil)

 In above code we did following things 
1) posted notification using post() method of NotificationCenter, it takes following parameters
  • name: name of the notification, in swift it take parameter of type Notification class.
  • object: object who triggers this notification, can be nil
  • userInfo: information associated with the notification, it takes NSDictionary and can be nil if there is no information you want while receiving the notification.

 Where to go from here :

In this post we learn how to use or implement NotificationCenter in Swift3 in our iOS app. If you have any question please free to comment. Happy coding 🙂