Push Notifications in SwiftUI for total beginners

Tanya Bond
4 min readMay 19, 2024

--

What are push notifications? They are pretty much real-time alerts popping up on your device. It is a crucial feature for apps since they enable developers to send information to users. Today, I’ll briefly walk through the steps required to implement push notifications in a SwiftUI application.

First things first!

Let’s create our SwiftUI App by navigating to “File” -> “New” -> “Project” -> “App”:

Before sending push notifications, we need to generate an iOS Push Certificate! Here are the steps you need to go through (it looks intimidating but it’s not, I promise!):

  • Go to your Apple Developer account. (If you don’t have it -> Check here).
  • In Certificates, Identifiers & Profiles select “Identifiers” and click the “+” button to create a new App ID.
  • Fill in the necessary details (you can find Bundle ID in the “General” tab of your Xcode project) and ensure that the “Push Notifications” service is enabled.
  • Now, when you see your new App ID in the “Identifiers” section, scroll to the “Push Notifications” section and click “Configure”.
  • First, you need to create a new certificate. When you’re done, choose this file as your new certificate, download, and save the certificate file.
  • You will now see it in your list of certificates.

The boring part is DONE.

Next step — Enable Push Notifications in your app

In the “Signing & Capabilities” tab click “+ Capability” and add “Push Notifications”.

You can also add “Background Modes” and select the “Remote notifications” option.

Next steps — request the user’s permission to receive notifications and register the device with Apple Push Notification Service (APNs)

import SwiftUI
import UserNotifications

@main
struct YourApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self)

var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}

class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
if granted {
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
return true
}

func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Convert device token to string
let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
let token = tokenParts.joined()
print("Device Token: \(token)")
// Send token to server
}

func application(_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register: \(error)")
}
}

Next step — Handle Incoming Notifications

// Set the Delegate

class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {

func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
if granted {
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
return true
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound, .badge])
}
}

We covered the basics of setting up push notifications and handling them. Now read through the documentation, and read this nice article that gives you a detailed explanation for different types of push notifications.

Don’t forget to test!

Here is an Apple article that shows how to test push notifications in iOS app. And another one!

As you can see, implementing push notifications in the iOS app requires a lot of initial configuration. But with push notifications integrated, you can enhance user engagement by delivering timely and relevant updates directly to your users’ devices. So I highly recommend you to go through the resources I provided to learn more about this feature!

--

--

Tanya Bond

iOS Developer with experience in Web Development and Engineering Management. Based in Cali 🌴🇺🇸