Why this happens
Push notifications require coordination between your app, Apple Push Notification service (APNs), and your server. The app must explicitly request user permission, register with APNs to receive a unique device token, and forward that token to your backend. Missing any step—permission request, capability entitlement, token handling, or server-side certificate/key configuration—results in notifications never arriving.
Modern iOS (10+) uses the UserNotifications framework instead of the deprecated UIUserNotificationSettings API. The delegate methods also shifted from UIApplicationDelegate to UNUserNotificationCenterDelegate for foreground presentation and custom actions.
How to fix it
1. Add the Push Notifications capability
- Open the project navigator → select your target → Signing & Capabilities.
- Click + Capability, search Push Notifications, and add it.
- Still in Signing & Capabilities, add Background Modes and check Remote notifications.
Xcode updates the entitlements file and provisions the App ID automatically when you build.
2. Request authorization and register with APNs
In AppDelegate.swift (or your UIApplicationDelegate adopter):
import UIKit
import UserNotifications
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().delegate = self
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
guard granted else { return }
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
}
return true
}
// Called when APNs successfully returns a device token
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
print("Device token: \(tokenString)")
// TODO: Send tokenString to your server
}
// Called when registration fails
func application(_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("APNs registration failed: \(error)")
}
}
Key points
– Always call registerForRemoteNotifications() on the main queue after authorization succeeds.
– Convert the Data token to a hex string before sending to your server.
– Store the token securely; treat it like a credential.
3. Handle incoming notifications
Foreground presentation (iOS 10+)
Implement UNUserNotificationCenterDelegate:
extension AppDelegate: UNUserNotificationCenterDelegate {
// Called when a notification arrives while the app is in the foreground
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// Show banner, play sound, update badge even in foreground
completionHandler([.banner, .sound, .badge])
}
// Called when the user taps a notification (any state)
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Navigate or handle payload
print("User tapped notification: \(userInfo)")
completionHandler()
}
}
Background / terminated launch
If the app launches from a notification tap, didFinishLaunchingWithOptions contains the payload:
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if let remoteNotification = launchOptions?[.remoteNotification] as? [AnyHashable: Any] {
// Handle payload
print("Launched from notification: \(remoteNotification)")
}
// ... authorization code from step 2
return true
}
4. Server-side essentials (checklist)
- Authentication: Use APNs Auth Key (
.p8) with JWT or legacy certificate (.p12). Auth Key is preferred—one key works for all apps in the team. - Endpoint:
api.push.apple.com(production) orapi.sandbox.push.apple.com(development). - Payload: JSON with
apsdictionary containingalert,badge,sound, and custom keys. - Topic: Your app’s bundle identifier.
- Expiration: Set
apns-expirationheader; omit for immediate delivery only.
5. Test on a physical device
Simulators cannot receive remote push notifications. Build and run on a device signed with a provisioning profile that includes the Push Notifications entitlement. Use the Console app (macOS) to filter apsd logs if tokens don’t arrive.
How to prevent it
- Enable Push Notifications and Background Modes → Remote notifications before first build.
- Request authorization once at launch; cache the user’s decision.
- Send the device token to your server every launch—tokens can rotate.
- Handle
UNUserNotificationCenterDelegatefor foreground banners and tap responses. - Use APNs Auth Key (
.p8) instead of certificates to avoid yearly renewal. - Test with both sandbox and production environments; they use different endpoints.
FAQ
Why does didRegisterForRemoteNotificationsWithDeviceToken never fire?
The capability is missing, the provisioning profile doesn’t include Push Notifications, or you’re testing on a simulator. Verify the entitlement in the built app with codesign -d --entitlements :- <app> and ensure you’re on a real device.
Can I use the same device token for sandbox and production?
No. Sandbox and production tokens are different and not interchangeable. Your server must store the environment alongside each token.
How do I know if the user disabled notifications in Settings?
Call UNUserNotificationCenter.current().getNotificationSettings { settings in … } and inspect settings.authorizationStatus. It returns .denied, .notDetermined, or .authorized (or .provisional / .ephemeral).
Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.
