Implementing Push Notifications in iOS Swift 3: A Comprehensive Guide

Understanding Push Notifications in iOS Swift 3

Push notifications are a powerful feature that allows developers to send notifications to their users even when the app is not running. In this article, we’ll explore how to set up and receive push notifications on an iOS app using Swift 3.

Introduction to Firebase Cloud Messaging (FCM)

Before diving into iOS push notifications, it’s essential to understand the role of FCM. FCM is a cloud-based messaging service provided by Google that allows developers to send targeted messages to their users. In this case, we’ll use FCM as our messaging service for the push notifications.

Setting Up Push Notifications in iOS

To set up push notifications on an iOS app, we need to follow these steps:

Step 1: Register for Push Notifications

We start by registering for push notifications in the application(_:didFinishLaunchingWithOptions:) method of our app delegate. This is where we create a new instance of UNUserNotificationCenter and set its delegate.

func setupNotifications(_ application: UIApplication) {
    let center  = UNUserNotificationCenter.current()
    center.delegate = self

    center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in }
}

Step 2: Handle Device Token Registration

Next, we need to handle the device token registration. This is where we get the device token and store it securely.

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    print("Notifications registration succeeded!")
    // Store the device token securely
}

Step 3: Handle Notification Registration

We also need to handle notification registration. This is where we request permission from the user to receive notifications.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    setupNotifications(application)
    return true
}

Step 4: Handle Notification Data

Once we’ve received a notification, we need to handle the notification data. This is where we get the notification message and handle it accordingly.

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    // Handle notification message clicked
}

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (_ options: UNNotificationPresentationOptions) -> Void) {
    // Handle notification data
}

Handling Inactive App Push Notifications

Now that we’ve set up push notifications, let’s discuss how to handle inactive app push notifications. When an app is inactive, the device token changes every 2 weeks due to security restrictions. This means that our application(_:didRegisterForRemoteNotificationsWithDeviceToken:) method won’t be called after the initial registration.

To overcome this issue, we need to use the FCM registration token. We can get the FCM registration token by calling the messaging(_:messaging:didReceiveRegistrationToken:) method.

func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
    print("Firebase registration token: \(fcmToken)")
    let dataDict:[String: String] = ["token": fcmToken]
    NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
}

By using the FCM registration token, we can receive push notifications even when our app is inactive.

Example Use Case

Here’s an example of how you can use these concepts in your own project:

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        setupNotifications(application)
        return true
    }

    func setupNotifications(_ application: UIApplication) {
        let center  = UNUserNotificationCenter.current()
        center.delegate = self

        center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in }
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("Notifications registration succeeded!")
    }

    func userNotificationCenter(_ center: UNUserセンター, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        // Handle notification message clicked
    }

    func userCenterer(_ center: UNUserCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (_ options: UNNotificationPresentationOptions) -> Void) {
        // Handle notification data
    }
}

In this example, we’ve implemented the necessary delegate methods to handle push notifications.

Conclusion

Push notifications are a powerful feature that allows developers to send targeted messages to their users. In this article, we’ve explored how to set up and receive push notifications on an iOS app using Swift 3. We’ve covered registration for push notifications, handling device token registration, notification registration, and handling inactive app push notifications.

By following these steps and understanding the concepts discussed in this article, you should be able to implement push notifications in your own iOS project.

Additional Resources

By leveraging these resources and following best practices, you can create a robust push notification system for your iOS app.


Last modified on 2025-02-25