DEV Community

Raaju Pahlowan
Raaju Pahlowan

Posted on Edited on

Building a Unified Push Notification Handler with Deep Linking in iOS

Push notifications start out simple: show a banner, open the app. Then the product team adds a new notification type, then another, and soon you have twenty of them, each expected to open a different screen. If every type is handled by its own if branch inside the app delegate, the code becomes impossible to maintain.

In this article I'll show the structure I use for FCM and APNs notifications in a UIKit app: one entry point for every notification, typed payloads, local persistence, and a deep-link router that works even when the app was killed.

1. Set up one entry point

All notification events should flow through a single object. Make it the UNUserNotificationCenter delegate, and set it before the app finishes launching, otherwise you can miss a tap that cold-starts the app.

final class NotificationCoordinator: NSObject, UNUserNotificationCenterDelegate {
    static let shared = NotificationCoordinator()
    private let router = DeepLinkRouter.shared
    private let store = NotificationStore()

    // Notification arrives while the app is in the foreground
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification) async
                                -> UNNotificationPresentationOptions {
        handleReceived(notification.request.content.userInfo)
        return [.banner, .sound, .badge]
    }

    // User tapped the notification
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse) async {
        let userInfo = response.notification.request.content.userInfo
        handleReceived(userInfo)
        if let payload = NotificationPayload(userInfo: userInfo) {
            router.route(to: payload.destination)
        }
    }

    private func handleReceived(_ userInfo: [AnyHashable: Any]) {
        guard let payload = NotificationPayload(userInfo: userInfo) else { return }
        store.save(payload)
    }
}
Enter fullscreen mode Exit fullscreen mode

In application(_:didFinishLaunchingWithOptions:), assign it before anything else:

UNUserNotificationCenter.current().delegate = NotificationCoordinator.shared

2. Turn raw payloads into typed models

The userInfo dictionary is untyped, so a typo in a key can break things silently. Convert it into a model once, at the edge, and use only that model afterward.

enum NotificationType: String {
    case jobMatch = "job_match"
    case applicationUpdate = "application_update"
    case message = "message"
    case promotion = "promotion"
    // ...add new types here
}

struct NotificationPayload {
    let id: String
    let type: NotificationType
    let title: String
    let body: String
    let params: [String: String]
    let receivedAt = Date()

    init?(userInfo: [AnyHashable: Any]) {
        guard let typeRaw = userInfo["type"] as? String,
              let type = NotificationType(rawValue: typeRaw) else { return nil }
        let aps = userInfo["aps"] as? [String: Any]
        let alert = aps?["alert"] as? [String: Any]
        self.id = userInfo["gcm.message_id"] as? String ?? UUID().uuidString
        self.type = type
        self.title = alert?["title"] as? String ?? ""
        self.body = alert?["body"] as? String ?? ""
        self.params = (userInfo["params"] as? [String: String]) ?? [:]
    }
}
Enter fullscreen mode Exit fullscreen mode

Returning nil for an unknown type means an old app version ignores notification types it doesn't understand, instead of crashing.

3. Map each type to a destination

Instead of a screen decision scattered across the code, describe every destination as an enum, and let each notification type produce one:

enum Destination {
    case jobDetail(id: String)
    case applicationStatus(id: String)
    case chat(threadID: String)
    case home
}

extension NotificationPayload {
    var destination: Destination {
        switch type {
        case .jobMatch:
            return params["job_id"].map(Destination.jobDetail) ?? .home
        case .applicationUpdate:
            return params["application_id"].map(Destination.applicationStatus) ?? .home
        case .message:
            return params["thread_id"].map(Destination.chat) ?? .home
        case .promotion:
            return .home
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Adding a new notification type now means adding one enum case and one line here. Always provide a fallback such as .home, because a payload with a missing ID shouldn't leave the user on a blank screen.

4. Route safely, even on a cold start

When a user taps a notification while the app is closed, the tap callback can fire before your root view controller exists. If you navigate immediately, nothing happens. The fix is to queue the destination until the UI is ready.

final class DeepLinkRouter {
    static let shared = DeepLinkRouter()
    private var pending: Destination?
    private var isReady = false

    func route(to destination: Destination) {
        guard isReady else { pending = destination; return }
        navigate(to: destination)
    }

    // Call this once the main screen has appeared
    func markReady() {
        isReady = true
        if let destination = pending {
            pending = nil
            navigate(to: destination)
        }
    }

    private func navigate(to destination: Destination) {
        DispatchQueue.main.async {
            guard let nav = UIApplication.topNavigationController() else { return }
            switch destination {
            case .jobDetail(let id):
                nav.pushViewController(JobDetailViewController(jobID: id), animated: true)
            case .applicationStatus(let id):
                nav.pushViewController(ApplicationStatusViewController(applicationID: id), animated: true)
            case .chat(let threadID):
                nav.pushViewController(ChatViewController(threadID: threadID), animated: true)
            case .home:
                nav.popToRootViewController(animated: true)
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The same queue also covers a related case: the user taps a notification while logged out. Hold the destination, send them through login, then call markReady() and deliver it.

5. Persist notifications locally

An in-app notification list needs every notification stored, including ones the user never tapped. Because everything already passes through one coordinator, saving is a single call. For a small history, a Codable file in the app's documents folder works. For a larger one, use Core Data or Realm.

final class NotificationStore {
    private let url = FileManager.default
        .urls(for: .documentDirectory, in: .userDomainMask)[0]
        .appendingPathComponent("notifications.json")

    func save(_ payload: NotificationPayload) { /* append and write, de-duplicate by payload.id */ }
    func all() -> [NotificationPayload] { /* read and decode */ [] }
}
Enter fullscreen mode Exit fullscreen mode

De-duplicate by ID. The same notification can reach you twice, once on arrival and again on tap.

6. Connect FCM and APNs

With Firebase Cloud Messaging, you register for remote notifications, hand the APNs token to Firebase, and send the FCM token to your backend:

func application(_ application: UIApplication,
                 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    Messaging.messaging().apnsToken = deviceToken
}

extension AppDelegate: MessagingDelegate {
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
        guard let fcmToken else { return }
        // send fcmToken to your backend
    }
}
Enter fullscreen mode Exit fullscreen mode

The FCM token can change, so upload it every time this callback fires, not only at first login.

7. Test every type

I keep a small list of sample payloads, one per notification type, and run them through the simulator with xcrun simctl push:

bash
xcrun simctl push booted com.example.app payload-job-match.json

Test three states for each type: app in the foreground, app in the background, and app force-quit. Most deep-link bugs show up only in the third.

Wrapping up

The structure comes down to four rules: one entry point, typed payloads, an enum of destinations, and a router that waits until the UI is ready. With that in place, adding the twenty-first notification type takes a few lines instead of a rewrite.

I'm Raaju Pahlowan, an iOS developer in Dhaka, Bangladesh, working with Swift, SwiftUI and UIKit. You can see my projects at raajupahlowan.github.io and connect with me on LinkedIn.

Top comments (0)