Push Notifications Tutorial: Getting Started
Push notifications allow developers to reach users, even when users aren’t actively using an app! In this tutorial, you’ll learn how to configure your app to receive push notifications and to display them to your users or perform other tasks. By Chuck Krutsinger .
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Push Notifications Tutorial: Getting Started
35 mins
- Getting Started
- Sending and Receiving Push Notifications
- Configuring the App
- Enabling the Push Notification Service
- Asking for User Notifications Permission
- Registering With APNs
- Sending a Simulated Push Notification
- Looking at a Basic Push Notification
- Handling Push Notifications
- Understanding What Happens When You Receive a Push Notification
- Working With Actionable Notifications
- Handling Notification Actions
- Sending to a Real Device
- Troubleshooting Common Issues
- Using Silent Push Notifications
- Where to Go From Here?
iOS developers love to imagine people using their awesome app constantly. But, of course, users will sometimes have to close the app and perform other activities. Laundry doesn’t fold itself, you know! Happily, push notifications allow developers to reach users and perform small tasks — even when users aren’t actively using the app! In this tutorial, you’ll learn how to:
- Configure your app to receive push notifications.
- Display them to your users or perform other tasks.
Getting Started
What are push notifications? They are messages sent to your app through the Apple Push Notification service (APNs) even if your app isn’t running or the phone is sleeping. What can you use push notifications for?
- Display a short text message, called an alert, that draws attention to something new in your app.
- Play a notification sound.
- Set a badge number on the app’s icon to let the user know there are new items.
- Provide actions the user can take without opening the app.
- Show a media attachment.
- Be silent, allowing the app to perform a task in the background.
- Group notifications into threads.
- Edit or remove delivered notifications.
- Run code to change your notification before displaying it.
- Display a custom, interactive UI for your notification.
- And probably more.
This tutorial covers many of these uses to help you get started creating push notifications in your apps. To complete this tutorial, you’ll need the following:
- Xcode 11.4 or later. Earlier versions of Xcode don’t support push notifications using the simulator.
- An Apple Developer Program membership to be able to compile the app with the Push Notifications entitlement.
To send and receive push notifications, you must perform three main tasks:
- Configure your app and register it with the APNs.
- Send a push notification from a server to specific devices via APNs. You’ll simulate that with Xcode.
- Use callbacks in the app to receive and handle push notifications.
Sending push notifications is a responsibility of your app’s server component. Many apps use third parties to send push notifications. Others use custom solutions or popular libraries (such as Houston). You’ll only touch on sending push messages in this tutorial, so be sure to check out the Where to Go From Here? section to build on your knowledge of push notifications.
To get started, download the WenderCast starter project using the Download Materials button at the top or bottom of this tutorial. WenderCast is everyone’s go-to source for raywenderlich.com podcasts and breaking news.
In the starter folder, open WenderCast.xcodeproj. Select WenderCast in the Project navigator, then select the WenderCast target. In the General & Capabilities tab, select your development team. Build and run in a simulator.
WenderCast displays a list of raywenderlich.com podcasts and lets users play them. But it doesn’t let users know when a new podcast is available and the News tab is empty! You’ll soon fix these issues with the power of push notifications.
Sending and Receiving Push Notifications
Configuring the App
Security is very important for push notifications. You don’t want anyone else to send push notifications to your users through your app. You’ll need to perform several tasks to configure your app to securely receive push notifications.
Enabling the Push Notification Service
First, you have to change the bundle identifier. In Xcode, highlight WenderCast in the Project navigator, then select the WenderCast target. Select General, then change Bundle Identifier to something unique so Apple’s push notification server can direct pushes to this app.
Next, you need to create an App ID in your developer account and enable the push notification entitlement. Xcode has a simple way to do this: With the WenderCast target still selected, click the Signing & Capabilities tab and then click the + Capability button. Type “push” in the filter field and press Enter.
After adding the push notifications entitlement, your project should look like this:
Behind the scenes, this creates the App ID and then adds the push notifications entitlement to it. You can log into the Apple Developer Center to verify this:
That’s all you need to configure for now. You are ready to start enhancing the app.
Asking for User Notifications Permission
There are two steps you take to register for push notifications. First, you must get the user’s permission to show notifications. Then, you can register the device to receive remote (push) notifications. If all goes well, the system will then provide you with a device token, which you can think of as an “address” to this device.
In WenderCast, you’ll register for push notifications immediately after the app launches. Ask for user permissions first.
Open AppDelegate.swift and add the following to the top of the file:
import UserNotifications
Then, add the following method to the end of AppDelegate
:
func registerForPushNotifications() {
//1
UNUserNotificationCenter.current()
//2
.requestAuthorization(options: [.alert, .sound, .badge]) { granted, _ in
//3
print("Permission granted: \(granted)")
}
}
What this code does:
-
UNUserNotificationCenter
handles all notification-related activities in the app, including push notifications. - You invoke
requestAuthorization(options:completionHandler:)
to (you guessed it) request authorization to show notifications. The passedoptions
indicate the types of notifications you want your app to use — here you’re requesting alert, sound and badge. - The completion handler receives a Bool that indicates whether authorization was successful. In this case, you simply print the result.
- .badge: Display a number on the corner of the app’s icon.
- .sound: Play a sound.
- .alert: Display a text notification.
- .carPlay: Display notifications in CarPlay.
- .provisional: Post non-interrupting notifications. The user won’t get a request for permission if you use only this option, but your notifications will only show silently in the Notification Center.
- .providesAppNotificationSettings: Indicate that the app has its own UI for notification settings.
- .criticalAlert: Ignore the mute switch and Do Not Disturb. You’ll need a special entitlement from Apple to use this option, because it’s meant only for very special use cases.
requestAuthorization(options:completionHandler:)
can include any combination of UNAuthorizationOptions
:
- .badge: Display a number on the corner of the app’s icon.
- .sound: Play a sound.
- .alert: Display a text notification.
- .carPlay: Display notifications in CarPlay.
- .provisional: Post non-interrupting notifications. The user won’t get a request for permission if you use only this option, but your notifications will only show silently in the Notification Center.
- .providesAppNotificationSettings: Indicate that the app has its own UI for notification settings.
- .criticalAlert: Ignore the mute switch and Do Not Disturb. You’ll need a special entitlement from Apple to use this option, because it’s meant only for very special use cases.
Add the following near the end of application(_:didFinishLaunchingWithOptions:)
, just before the return
:
registerForPushNotifications()
Calling registerForPushNotifications()
here ensures the app will attempt to register for push notifications any time it’s launched.
Build and run. When the app launches, you should receive a prompt that asks for permission to send you notifications.
Tap Allow, and poof! The app can now display notifications. Great! But what if the user declines the permissions? Add this method inside AppDelegate
:
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { settings in
print("Notification settings: \(settings)")
}
}
First, you specified the settings you want. This method returns the settings the user has granted. For now, you’re printing them, but you’ll circle back here shortly to do more with this.
In registerForPushNotifications()
, replace the call to requestAuthorization(options:completionHandler:)
with the following:
UNUserNotificationCenter.current()
.requestAuthorization(
options: [.alert, .sound, .badge]) { [weak self] granted, _ in
print("Permission granted: \(granted)")
guard granted else { return }
self?.getNotificationSettings()
}
You’ve added a call to getNotificationSettings()
in the completion handler. This is important because the user can, at any time, go into the Settings app and change their notification permissions. The guard
avoids making this call in cases where permission wasn’t granted.