Keep Reading
If you enjoyed the post you just read, we have more to say!
Push notifications are a powerful tool for keeping users engaged, informed, and coming back to your app for more. Whether it’s a timely reminder, an exciting update, or a personalized message, push notifications significantly improve the user experience while boosting retention.
Best of all, push notifications are available on nearly all browsers, devices, and operating systems. However, Apple iOS has more requirements for push notifications, so it’s critical for businesses and developers to understand these differences. iOS is notorious for its stringent security requirements and user-first privacy controls, so design push notifications for your iOS app with these requirements in mind.
In this guide, we’ll give you a comprehensive, step-by-step guide to implementing push notifications for iOS apps. This tutorial will walk you through the entire process, from setting up the necessary configurations and writing the code to testing and troubleshooting.
In this article:
Push notifications are messages sent from an app server to users' devices, prompting them to take action. Unlike in-app notifications, push notifications reach users even when they aren’t actively using your app.
They can appear on lock screens, notification centers, or as banners. For iOS apps, push notifications rely on the Apple Push Notification service (APNs), which routes these messages from your server to the target devices.
At a high level, iOS push notifications follow a three-step process:
This process is relatively straightforward, but remember that iOS push notifications must follow more stringent requirements than Android notifications. iOS implementation also has to account for:
Although iOS push notifications have a few more requirements and considerations, they’re still worth your time. Push notifications offer several advantages that make them an essential feature for enhancing user engagement and retention, including:
Setting up iOS push notifications is a technical process. Still, with the right toolkit and processes, developers can build effective push notifications that keep users coming back to your iOS app.
Integrating push notifications into your iOS app involves several processes, from initial setup to implementation and testing. Follow these steps to set up push notifications for your iOS app.
Start by getting your ducks in a row. To get started with integrating push notifications into your iOS app, you’ll need the following tools and software:
Now that you have the necessary tools and an Apple Developer account, it's time to set up your iOS project in Xcode. Launch Xcode and click on "Create a new Xcode project" or select File > New > Project > App from the menu bar.
Configure your project by filling out these details:
Now that you’ve set up the project, you’ll need to enable push notifications. Go to the project settings tab > Capabilities. Check the boxes and toggles to turn on Push Notifications, Background Modes, and Remote Notifications.
To send push notifications to your iOS app, you need to configure the Apple Push Notification service (APNs). This involves registering your app with APNs, creating a push notification certificate, and generating an APNs Auth Key.
Visit the Apple Developer Console and sign in. Create an App ID and use it to create a push notification certificate. From there, you’ll generate a Certificate Signing Request (CSR). Once the system generates a certificate for you, download it and install it in Keychain Access. Save the certificate as a .p12 file, providing a password when prompted.
Next, go to Keys in the Apple Developer Console. Create a new key and download the Auth Key as a .p8 file. This file is only available for download once, so keep it somewhere safe!
With the foundational setup complete, it's time to integrate push notifications into your iOS app by updating your code. The ‘AppDelegate’ file responds to application-level events like push notifications, so this is where you’ll make most of the changes.
Add the following import statement at the top of your AppDelegate.swift file:
import UserNotifications
Register your app for push notifications using the application(_:didFinishLaunchingWithOptions:) method:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
UNUserNotificationCenter.current().delegate = self
registerForPushNotifications()
return true
}
func registerForPushNotifications() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
print("Permission granted: \(granted)")
guard granted else { return }
self.getNotificationSettings()
}
}
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { settings in
print("Notification settings: \(settings)")
guard settings.authorizationStatus == .authorized else { return }
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
Next, you’ll set up device token registration for remote notifications:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
let token = tokenParts.joined()
print("Device Token: \(token)")
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register: \(error)")
}
Now it’s time to request permission from the user to send notifications. This is a crucial step you take using the ‘registerForPushNotifications()’ method:
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
print("Permission granted: \(granted)")
guard granted else { return }
self.getNotificationSettings()
}
The app receives a device token when it successfully registers for remote notifications. This token must be sent to your server to send push notifications to this device:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
let token = tokenParts.joined()
print("Device Token: \(token)")
// Send the token to your server
}
Finally, you must conform to the UNUserNotificationCenterDelegate protocol to handle incoming notifications. Set the UNUserNotificationCenter delegate in the didFinishLaunchingWithOptions method:
UNUserNotificationCenter.current().delegate = self
Implement the userNotificationCenter(_:willPresent:withCompletionHandler:) and userNotificationCenter(_:didReceive:withCompletionHandler:) methods to handle notifications while the app is in the foreground and background, respectively:
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
// Handle the notification content here
print("Foreground Notification received: \(userInfo)")
completionHandler([.alert, .sound, .badge])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Handle the notification response here
print("Background Notification received: \(userInfo)")
completionHandler()
}
}
The most intensive coding is done, so pat yourself on the back! Now that you’ve set up the iOS app to receive push notifications, it’s time to send them.
There are a lot of push notification services out there, but Firebase Cloud Messaging (FCM) is one of the most popular options. This cross-platform messaging solution allows you to send notifications for less hassle.
To get started, you’ll need an FCM account. Create a new project and add your iOS app to the project. Register your app with the iOS bundle ID, download the GoogleService-Info.plist file, and add it to your Xcode project. Make sure to add it to the root directory of your project.
From there, import Firebase in your AppDelegate.swift file:
import Firebase
Next, configure Firebase in the application(_:didFinishLaunchingWithOptions:) method:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
UNUserNotificationCenter.current().delegate = self
registerForPushNotifications()
return true
}
Extend AppDelegate to conform to MessagingDelegate:
import Firebase
extension AppDelegate: MessagingDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
print("FCM Token: \(String(describing: fcmToken))")
// Send the FCM token to your server
}
}
Set the Messaging delegate in the application(_:didFinishLaunchingWithOptions:) method:
Messaging.messaging().delegate = self
You’ve worked hard to set up iOS push notifications, but you should always double-check your work before sending messages to real users. iOS simulators are a popular option, but they won’t work for testing push notifications, so it’s best to test this on an actual iOS device.
There’s also a Push Notifications Console within the Apple Developer Console that allows you to send test notifications to Apple devices through APNs. And if you’re setting up push notifications for an iOS PWA, webpushtest.com is an excellent free tool. Use your chosen push notification service to send a test notification to your device.
Problems are common with web development, and push notifications are no exception. Every app has its quirks, but here are some common issues to look for:
Push notifications are a powerful tool for increasing user engagement and retention for iOS apps. They require a few more steps than push notifications for Android devices, but iOS push notifications offer a much-needed lifeline between a business and its users.
You may need to get creative and customize implementation for your business’s unique needs. Still, the steps in this guide will set you up for iOS success.
But we’re willing to bet your users aren’t just active on iOS devices. They’re also on Slack, email, and other channels. Instead of creating push notifications for every single channel, go with MagicBell’s all-in-one solution. Create your free account now to start sending notifications in under an hour.
Yes, you can customize the appearance of push notifications by adding rich media such as images, videos, and interactive elements. You can also use the UNNotificationContent class to specify custom content.
iOS requires an Apple Developer Account, APNs, and explicit user permission to receive notifications. Android, on the other hand, requires a Firebase project and the Firebase API key. Android permissions are also declared in the manifest file and don’t require a runtime prompt for basic notifications.