SwiftUI: How to create your custom notification event and receive the event! Advanced Technique for your career

KD Knowledge Diet
2 min readJul 13, 2022

What comes to mind when you think of Notification? Just think for 3 seconds. When many developers hear the word “notification”, they think only of push notifications or push alarm. For reference, Notification mentioned here is not the alarm notification you are familiar with. Notification here can refer to events that occur within the app. Apple helps you catch a lot of events through this notification.

Some Useful AppEvents through Notification

Catch App Events

You can see from the code above that you can catch app lifecycle events happening in the application through NotificationCenter.

  • UIApplication.willResignActiveNotification
  • UIApplication.willTerminateNotification
  • UIApplication.willEnterForegroundNotification
  • UIApplication.didBecomeActiveNotification

You are not limited to these events. There are many more useful events happening in your application. Not only can you use these notifications created by Framework, you can also create your own event!

Create your own notification event

Create your own notification

This can be easily achieved. Just define your custom defined event with extension.

Post your event

Button with action that posts a notification

I created a button which posts my custom defined event when clicked. It also sends event with an object attached.

Receive your event

Receive an event

With help of onReceive modifier, you can easily receive your event and handle it according to your logic.

Entire Code

Entire Code

Conclusion

  • In Swift, NotificationCenter also handles app events.
  • You can create your own app events.
  • Post your event with Notification.default.post().
  • Receive your event with onReceive() modifier.

--

--

KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!