Swift
Custom Notifications
Swift 3
iOS Development
Programming Tutorial

How do you create custom notifications in Swift 3?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In Swift 3, “custom notifications” usually means custom app-internal notifications posted through NotificationCenter. This is a way for one part of the app to broadcast an event without directly depending on every listener.

That makes notifications useful for loose coupling, but they are still just one tool. The basic flow is: define a notification name, post it, and observe it somewhere else.

Define a Notification Name

The first step is to avoid raw strings spread across the codebase. In Swift 3, the common pattern is an extension on Notification.Name.

swift
1import Foundation
2
3extension Notification.Name {
4    static let userDidLogIn = Notification.Name("userDidLogIn")
5}

This gives you one central constant instead of several string literals that can drift out of sync.

Post the Notification

Once the name exists, any object can post it through NotificationCenter.default.

swift
1import Foundation
2
3class LoginService {
4    func completeLogin(username: String) {
5        NotificationCenter.default.post(
6            name: .userDidLogIn,
7            object: self,
8            userInfo: ["username": username]
9        )
10    }
11}

This notification carries:

  • a name,
  • an optional sender object,
  • and optional userInfo data.

That is the whole payload model for a basic custom notification.

Observe the Notification

In Swift 3, one of the most common observation styles uses selector-based observers.

swift
1import UIKit
2
3class ProfileViewController: UIViewController {
4
5    override func viewDidLoad() {
6        super.viewDidLoad()
7
8        NotificationCenter.default.addObserver(
9            self,
10            selector: #selector(handleUserDidLogIn(_:)),
11            name: .userDidLogIn,
12            object: nil
13        )
14    }
15
16    @objc private func handleUserDidLogIn(_ notification: Notification) {
17        let username = notification.userInfo?["username"] as? String
18        print("Logged in user: \(username ?? "unknown")")
19    }
20
21    deinit {
22        NotificationCenter.default.removeObserver(self)
23    }
24}

This is the classic Swift 3 pattern. The observer registers in viewDidLoad and unregisters in deinit.

Filtering by Sender

If you want to listen only to notifications from a specific object, pass that object into the observer call instead of nil.

swift
1NotificationCenter.default.addObserver(
2    self,
3    selector: #selector(handleUserDidLogIn(_:)),
4    name: .userDidLogIn,
5    object: loginService
6)

That can reduce accidental cross-talk in larger apps where the same event name may be used by several instances.

When userInfo Is Useful

userInfo is the simplest way to attach small bits of context to the event.

Example:

swift
1NotificationCenter.default.post(
2    name: .userDidLogIn,
3    object: self,
4    userInfo: [
5        "username": "alice",
6        "loginMethod": "password"
7    ]
8)

Then read it in the handler:

swift
1@objc private func handleUserDidLogIn(_ notification: Notification) {
2    let username = notification.userInfo?["username"] as? String
3    let method = notification.userInfo?["loginMethod"] as? String
4    print(username ?? "", method ?? "")
5}

Use keys consistently. If the event payload becomes large or complicated, that is often a sign the app may need a stronger abstraction than raw notifications.

When Notifications Are a Good Fit

Custom notifications work well when:

  • multiple parts of the app may care about the same event,
  • the sender should not know all receivers,
  • and the payload is small and event-like.

They are less ideal when:

  • one object has exactly one clear delegate,
  • the data contract is large or strongly typed,
  • or the interaction is really a direct request rather than a broadcast event.

In those cases, delegates, closures, or dedicated service calls are often cleaner.

Threading and UI Updates

NotificationCenter does not automatically move your code onto the main thread. If the notification leads to UI work, make sure the observer handles that correctly.

For example:

swift
1@objc private func handleUserDidLogIn(_ notification: Notification) {
2    DispatchQueue.main.async {
3        self.view.backgroundColor = .green
4    }
5}

That matters when notifications are posted from background work such as networking or file operations.

Common Pitfalls

One common mistake is using raw string names everywhere instead of centralizing them in a Notification.Name extension. That creates typo-prone code.

Another mistake is forgetting to remove observers in older selector-based patterns. That can lead to crashes or confusing behavior when objects outlive their intended lifecycle.

It is also easy to overuse notifications for everything. They are useful for broadcast events, but they make code harder to trace when used as a replacement for all direct communication.

Finally, userInfo is only a dictionary. If the payload contract is important, document the keys clearly and keep the data small and predictable.

Summary

  • In Swift 3, custom app notifications are usually created with NotificationCenter.
  • Define names in a Notification.Name extension instead of using raw strings.
  • Post notifications with an optional sender object and userInfo dictionary.
  • Observe them with addObserver and a selector, then remove observers when appropriate.
  • Use notifications for loosely coupled broadcast events, not for every kind of object communication.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.