The problem
Push notifications have more moving parts than any other system feature: a key on the developer site, a signed token on your server, a device token in your app, a permission the person can revoke, an optional extension, and a delivery service that drops or delays messages by design. When a push does not arrive, any one of those can be the cause, and none of them reports the failure on the device. Set each part up deliberately, in order, and keep a test path that isolates the server from the app.
Create an APNs auth key
Use token-based authentication. Apple’s token-based connection guide lists the advantages over certificates: it is stateless and faster, one key works from many servers, and one key can cover many of your company’s apps.
In Certificates, Identifiers & Profiles, create a key with APNs enabled. You get a 10-character Key ID and a .p8 file you can download once. Apple now offers two kinds:
- Team-scoped keys work for every topic in the team and are restricted to Sandbox or Production. Each environment allows at most two.
- Topic-specific keys cover chosen topics in one environment, up to 200 keys per environment and 400 topics per key.
Use separate Sandbox and Production keys. Store the .p8 in your secrets manager; anyone holding it can push to your users. If you suspect a leak, revoke it, create a new one, and close your existing HTTP/2 connections.
Sign and refresh the JWT
Your server signs a JSON Web Token with the key. The header carries alg: ES256 and kid (the Key ID). The claims carry iss (your Team ID) and iat (issue time in seconds). Send it as authorization: bearer <token>.
The refresh rule trips up many servers. Apple says to refresh the token no more than once every 20 minutes and no less than once every 60 minutes. A token older than an hour gets 403 ExpiredProviderToken, and generating a new token for every request triggers errors too. Build a cache that reissues around the 30 to 50 minute mark.
Apple’s command-line guide shows the whole flow with openssl and curl, which is the fastest way to prove your key works before any server code exists:
TEAM_ID=ABCDE12345
AUTH_KEY_ID=KEY1234567
TOKEN_KEY_FILE_NAME=AuthKey_KEY1234567.p8
TOPIC=com.example.app
DEVICE_TOKEN=paste-device-token-here
APNS_HOST_NAME=api.sandbox.push.apple.com
JWT_ISSUE_TIME=$(date +%s)
JWT_HEADER=$(printf '{ "alg": "ES256", "kid": "%s" }' "$AUTH_KEY_ID" | openssl base64 -e -A | tr -- '+/' '-_' | tr -d =)
JWT_CLAIMS=$(printf '{ "iss": "%s", "iat": %d }' "$TEAM_ID" "$JWT_ISSUE_TIME" | openssl base64 -e -A | tr -- '+/' '-_' | tr -d =)
JWT_SIGNED=$(printf "%s.%s" "$JWT_HEADER" "$JWT_CLAIMS" | openssl dgst -binary -sha256 -sign "$TOKEN_KEY_FILE_NAME" | openssl base64 -e -A | tr -- '+/' '-_' | tr -d =)
AUTHENTICATION_TOKEN="$JWT_HEADER.$JWT_CLAIMS.$JWT_SIGNED"
curl -v --http2 \
--header "apns-topic: $TOPIC" \
--header "apns-push-type: alert" \
--header "authorization: bearer $AUTHENTICATION_TOKEN" \
--data '{"aps":{"alert":{"title":"Test","body":"Hello from APNs"}}}' \
"https://$APNS_HOST_NAME/3/device/$DEVICE_TOKEN"
A 200 means APNs accepted it. Builds signed for development get sandbox tokens, which only work against api.sandbox.push.apple.com. TestFlight and App Store builds get production tokens for api.push.apple.com. Mixing the two is the most common “it works for me” bug, so store the environment next to every token on your server.
Register for a device token
Add the Push Notifications capability to the app target. Then register on every launch. Natalia Panferova’s remote push setup post explains why: tokens change, and an old one can stop working. In a SwiftUI app you need an app delegate for the callbacks.
import SwiftUI
import UIKit
import UserNotifications
final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
UNUserNotificationCenter.current().delegate = self
application.registerForRemoteNotifications()
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.map { String(format: "%02x", $0) }.joined()
Task { try await DeviceRegistry.upload(token: token) }
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: any Error) {
Diagnostics.report(error)
}
nonisolated func userNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification
) async -> UNNotificationPresentationOptions {
[.banner, .list, .sound]
}
}
@main
struct ExampleApp: App {
@UIApplicationDelegateAdaptor private var appDelegate: AppDelegate
var body: some Scene {
WindowGroup { ContentView() }
}
}
DeviceRegistry and Diagnostics are your own code. Set the delegate before launch finishes, or you miss the tap that launched the app. Without willPresent, notifications that arrive while the app is open are silently dropped from view; Natalia calls this out because it looks exactly like a delivery failure.
Registering does not need permission. Silent background pushes (content-available: 1) work without it. Alerts, sounds and badges need authorization.
Ask for permission at the right moment
You get one system prompt. Apple’s permission guide says to ask in context, for example right after someone creates their first reminder, so the value is obvious.
import UserNotifications
enum NotificationPermission {
static func requestIfNeeded() async -> Bool {
let center = UNUserNotificationCenter.current()
let settings = await center.notificationSettings()
switch settings.authorizationStatus {
case .authorized, .provisional, .ephemeral:
return true
case .denied:
return false
case .notDetermined:
return (try? await center.requestAuthorization(options: [.alert, .sound, .badge])) ?? false
@unknown default:
return false
}
}
}
When status is .denied, the prompt never shows again. Offer a button that opens your app’s page in Settings with UIApplication.openSettingsURLString.
Provisional authorization
Add .provisional to the options and the system grants permission immediately, with no prompt. Notifications then arrive quietly in Notification Center history only, with Keep and Turn Off buttons. Apple notes you can request this at first launch because the person decides only when they see a real notification.
Natalia Panferova’s provisional authorization post suggests the follow-up: once people have seen a few useful quiet notifications, show an in-app message explaining what full alerts add, with a link to Settings. This article recommends provisional for apps whose notifications are useful but not urgent (summaries, progress, reminders the person set up). For a messaging app, where the first notification must be a banner, ask explicitly instead.
Build the payload
Apple’s payload reference sets the hard limit: 4 KB for regular pushes, 5 KB for VoIP. Custom keys go next to aps, never inside it.
{
"aps": {
"alert": { "title": "Order shipped", "body": "Arrives Thursday." },
"sound": "default",
"thread-id": "order-48213",
"category": "ORDER_UPDATE",
"interruption-level": "active",
"relevance-score": 0.6,
"mutable-content": 1
},
"orderID": "48213"
}
thread-id groups related notifications. relevance-score (0 to 1) decides which of yours leads the notification summary. category connects to action buttons you register at launch with UNNotificationCategory. Apple also warns not to put sensitive data in a payload unencrypted; decrypt it on device in a service extension.
Interruption levels and Time Sensitive
Since iOS 15, every notification has an interruption level: passive, active (the default), time-sensitive or critical. The HIG on managing notifications gives the behavior: Time Sensitive breaks through Focus and scheduled summaries; Critical also overrides the Ring/Silent switch and needs an entitlement from Apple.
To send Time Sensitive notifications, the WWDC21 session Send communication and Time Sensitive notifications says to enable the Time Sensitive capability in Xcode, then set "interruption-level": "time-sensitive" in the payload or content.interruptionLevel = .timeSensitive locally. The HIG is firm on use: only for something happening now or within an hour, and never for marketing. The system asks people whether your Time Sensitive notifications deserve the privilege and lets them turn it off, so overuse costs you the feature.
Modify pushes in a service extension
A Notification Service Extension (iOS 10) runs before an alert is shown. Use it to download an image, decrypt text, or fill in data from shared storage. Apple’s guide sets the conditions: the payload must have mutable-content: 1 and an alert with a title, subtitle or body, and alerts must be allowed for your app. Badge-only and silent pushes never reach it.
You get about 30 seconds. If you do not call the content handler in time, serviceExtensionTimeWillExpire() runs and you must deliver your best attempt immediately, or the system shows the original.
import UserNotifications
final class NotificationService: UNNotificationServiceExtension {
private var contentHandler: ((UNNotificationContent) -> Void)?
private var bestAttempt: UNMutableNotificationContent?
private var download: Task<Void, Never>?
override func didReceive(
_ request: UNNotificationRequest,
withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void
) {
self.contentHandler = contentHandler
guard let content = request.content.mutableCopy() as? UNMutableNotificationContent else {
contentHandler(request.content)
return
}
bestAttempt = content
guard let link = content.userInfo["imageURL"] as? String, let url = URL(string: link) else {
contentHandler(content)
return
}
download = Task {
if let attachment = try? await Self.attachment(from: url) {
content.attachments = [attachment]
}
contentHandler(content)
}
}
override func serviceExtensionTimeWillExpire() {
download?.cancel()
if let contentHandler, let bestAttempt {
contentHandler(bestAttempt)
}
}
private static func attachment(from url: URL) async throws -> UNNotificationAttachment {
let (temporary, _) = try await URLSession.shared.download(from: url)
let destination = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString)
.appendingPathExtension(url.pathExtension)
try FileManager.default.moveItem(at: temporary, to: destination)
return try UNNotificationAttachment(identifier: "image", url: destination)
}
}
The attachment must be a local file with an extension the system recognizes, which is why the code moves the download to a path with the original extension. Antoine van der Lee’s rich notifications article walks through the same pattern and adds two lessons: keep the best-attempt copy so a timeout still shows something sensible, and test rich notifications on a real device. The UNNotificationServiceExtension API predates Swift concurrency, so expect to mark the class @unchecked Sendable or isolate the stored handler if your extension target uses strict concurrency checking.
Custom UI with a content extension
A Notification Content Extension (UNNotificationContentExtension, iOS 10) replaces the expanded notification UI with your own view controller for a category you choose in its Info.plist. Use it when the notification needs a map, a chart or a live preview. Keep it fast and static; it is not a mini app.
Handle taps and actions
userNotificationCenter(_:didReceive:) fires when the person taps the notification or an action button. Read response.actionIdentifier and the payload’s custom keys, route to the right screen, and return. Antoine’s rule is to always call the completion handler; with the async variant, return promptly.
Test
Apple’s Push Notifications Console is the best single test tool. It sends to a device token or a channel, builds payloads for each push type, keeps history for 30 days, and generates the equivalent curl command. In the development environment, its delivery log shows what happened to a push for up to seven days, keyed by the apns-unique-id APNs returns. It also validates device tokens and JWTs, and can generate a JWT in the browser without uploading your key. Only team admins can send to production.
Antoine’s article also points out that Xcode 11.4 and later can deliver a push payload to Simulator from the terminal, with xcrun simctl push booted com.example.app payload.json. That skips APNs entirely, which is ideal for UI and extension work. Use a device and the console to test the real path.
Traps
- Sandbox token to production host, or the reverse. Log which environment each token came from.
- JWT regenerated per request or kept longer than an hour.
- Delegate set too late, so the launch tap is lost.
- Missing
willPresent, so foreground pushes seem to vanish. - Service extension never runs because
mutable-contentor the alert text is missing. - Time Sensitive for promotions. People turn it off, and the HIG forbids it.
- Assuming delivery. Apple’s console guide notes that APNs may deliver immediately, defer, retry or discard a push depending on battery and network. Treat pushes as hints and fetch current state when the app opens.
Checklist
| Step | Where |
|---|---|
| APNs key per environment | Developer account, Keys |
| JWT cache, 20 to 60 minute refresh | Your server |
| Push Notifications capability | App target |
registerForRemoteNotifications() every launch |
App delegate |
| Permission in context or provisional | First meaningful moment |
willPresent and didReceive delegate |
Set before launch ends |
mutable-content: 1 for extensions |
Payload |
| Time Sensitive capability | Only if truly needed |
| First test | Push Notifications Console |
Sources and further reading
- Establishing a token-based connection to APNs Apple Developer Documentation
- Asking permission to use notifications Apple Developer Documentation
- Generating a remote notification Apple Developer Documentation
- Modifying content in newly delivered notifications Apple Developer Documentation
- Testing notifications using the Push Notification Console Apple Developer Documentation
- Sending push notifications using command-line tools Apple Developer Documentation
- Managing notifications Apple Human Interface Guidelines
- Send communication and Time Sensitive notifications Apple, WWDC21
- iOS app setup for remote push notifications Natalia Panferova, Nil Coalescing
- Sending trial notifications with provisional authorization on iOS Natalia Panferova, Nil Coalescing
- Rich notifications on iOS explained in Swift Antoine van der Lee, SwiftLee