[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6E6KQNPJD3DEVDJM1FZ5B02":3,"skill-same:01M6E6KQNPJD3DEVDJM1FZ5B02":65},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":37,"linkOnly":38,"markdownContent":39,"markdownBody":40,"frontMatter":41,"refName":42,"commitSha":43,"skillDirectory":44,"forksCount":45,"repositoryHtmlUrl":46,"repositoryHomepageUrl":47,"ownerHtmlUrl":48,"ownerBlogUrl":6,"ownerDescription":49,"updatedAt":50,"install":51,"resources":64},"01M6E6KQNPJD3DEVDJM1FZ5B02","axiom-push-notifications",null,"Use when implementing remote or local push notifications, requesting notification permission, managing APNs device tokens, adding notification actions\u002Fcategories, building service extensions, or debugging push delivery failures. Covers APNs, FCM, Live Activity push transport, broadcast push, communication notifications, Focus interaction.","ComeOnOliver\u002Fskillshub","ComeOnOliver","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F43215937?v=4","01M6E5JNFECJAAVFE0W7SMWWD2","Haoran Shu","01M6E5JNNDQS7AJZDYFQ8TPZCK",67,"MIT","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002FCharlesWiltgen\u002FAxiom\u002Faxiom-push-notifications\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36],"axiom push notifications","push","notifications","push notifications","permission","interaction","live","service","apns","tokens","local","debugging","focus","delivery","device","use","actions","communication","2026-11-10 10:12:30",false,"---\nname: axiom-push-notifications\ndescription: Use when implementing remote or local push notifications, requesting notification permission, managing APNs device tokens, adding notification actions\u002Fcategories, building service extensions, or debugging push delivery failures. Covers APNs, FCM, Live Activity push transport, broadcast push, communication notifications, Focus interaction.\nlicense: MIT\n---\n\n# Push Notifications\n\nRemote and local notification patterns for iOS. Covers permission flow, APNs registration, token management, payload design, actionable notifications, rich notifications with service extensions, communication notifications, Focus interaction, and Live Activity push transport.\n\n## When to Use This Skill\n\nUse when you need to:\n- ☑ Implementing remote (APNs) push notifications\n- ☑ Requesting notification permissions\n- ☑ Managing device tokens and server sync\n- ☑ Adding actionable notifications with categories\u002Factions\n- ☑ Building rich notifications with service extensions\n- ☑ Communication notifications with avatars (iOS 15+)\n- ☑ Time Sensitive or Critical alerts\n- ☑ Updating Live Activities via push (transport layer)\n- ☑ Broadcast push for large audiences (iOS 18+)\n- ☑ Local notification scheduling\n\n## Example Prompts\n\n\"How do I set up push notifications?\"\n\"When should I ask for notification permission?\"\n\"My push notifications aren't arriving\"\n\"How do I add buttons to notifications?\"\n\"How do I show images in push notifications?\"\n\"How do I send push updates to a Live Activity?\"\n\"What's the difference between APNs token and FCM token?\"\n\"How do I make notifications break through Focus mode?\"\n\"My notifications work in development but not production\"\n\"How do I handle notification taps to open a specific screen?\"\n\n## Red Flags\n\nSigns you're making this harder than it needs to be:\n\n- ❌ Requesting permission on first launch before user understands value\n- ❌ Caching device tokens locally instead of requesting fresh each launch\n- ❌ Sending the same token to sandbox AND production APNs\n- ❌ Using `content-available: 1` without understanding silent push throttling (~2-3\u002Fhour)\n- ❌ Not implementing `serviceExtensionTimeWillExpire` fallback\n- ❌ Force-unwrapping device token or assuming registration always succeeds\n- ❌ Hardcoding APNs host instead of switching sandbox\u002Fproduction by environment\n- ❌ Setting `apns-priority: 10` for all notifications (drains battery, gets throttled)\n- ❌ Exceeding 4KB payload without realizing APNs silently rejects it\n- ❌ Using FCM without disabling method swizzling when you have custom delegate handling\n- ❌ Not handling foreground notification presentation (notifications silently dropped)\n- ❌ Overusing Time Sensitive interruption level (erodes user trust, they'll disable all notifications)\n\n## Mandatory First Steps\n\nBefore implementing any push notification feature:\n\n### 1. Enable Push Notification Capability\n\n- Xcode: Target → Signing & Capabilities → + Push Notifications\n- Adds `aps-environment` entitlement\n- Verify in Apple Developer Portal that the App ID has Push Notifications enabled\n\n### 2. Register for Remote Notifications\n\n```swift\n\u002F\u002F AppDelegate\nfunc application(_ application: UIApplication,\n                 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {\n    UNUserNotificationCenter.current().delegate = self\n    UIApplication.shared.registerForRemoteNotifications()\n    return true\n}\n\nfunc application(_ application: UIApplication,\n                 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {\n    let token = deviceToken.map { String(format: \"%02x\", $0) }.joined()\n    sendTokenToServer(token) \u002F\u002F Never cache locally — tokens change\n}\n\nfunc application(_ application: UIApplication,\n                 didFailToRegisterForRemoteNotificationsWithError error: Error) {\n    \u002F\u002F Simulator cannot register. Log, don't crash.\n}\n```\n\n### 3. Request Authorization (in context, not at launch)\n\n```swift\nlet center = UNUserNotificationCenter.current()\nlet granted = try await center.requestAuthorization(options: [.alert, .sound, .badge])\nif granted {\n    await MainActor.run { UIApplication.shared.registerForRemoteNotifications() }\n}\n```\n\nRequest when user action makes notification value obvious (e.g., after scheduling a reminder, subscribing to updates). The system prompts only once — bad timing means permanent denial.\n\n## Permission Flow\n\n### Pattern 1: Standard Authorization\n\nRequest in context after user understands the value:\n\n```swift\nfunc subscribeToUpdates() async {\n    let center = UNUserNotificationCenter.current()\n    let settings = await center.notificationSettings()\n\n    switch settings.authorizationStatus {\n    case .notDetermined:\n        let granted = try? await center.requestAuthorization(options: [.alert, .sound, .badge])\n        if granted == true {\n            await MainActor.run { UIApplication.shared.registerForRemoteNotifications() }\n        }\n    case .authorized, .provisional:\n        \u002F\u002F Already have permission\n        break\n    case .denied:\n        \u002F\u002F Redirect to Settings\n        promptToOpenSettings()\n    case .ephemeral:\n        break\n    @unknown default:\n        break\n    }\n}\n```\n\n### Pattern 2: Provisional Authorization (iOS 12+)\n\nNotifications appear quietly in Notification Center with Keep\u002FTurn Off buttons. No permission dialog shown to user.\n\n```swift\nlet granted = try await center.requestAuthorization(options: [.alert, .sound, .badge, .provisional])\n```\n\nGood for apps where users haven't yet discovered notification value. They see notifications quietly and choose to promote them.\n\n### Pattern 3: Authorization Status Check\n\nAlways check before scheduling or assuming permission:\n\n```swift\nlet settings = await UNUserNotificationCenter.current().notificationSettings()\nguard settings.authorizationStatus == .authorized else {\n    \u002F\u002F Handle missing permission\n    return\n}\n```\n\n### Pattern 4: Handling Denial\n\nRedirect to Settings when user has denied:\n\n```swift\nfunc promptToOpenSettings() {\n    \u002F\u002F iOS 16+\n    if let url = URL(string: UIApplication.openNotificationSettingsURLString) {\n        UIApplication.shared.open(url)\n    } else {\n        \u002F\u002F Fallback: general app settings\n        if let url = URL(string: UIApplication.openSettingsURLString) {\n            UIApplication.shared.open(url)\n        }\n    }\n}\n```\n\n## Token Management\n\n### Token Format\n\n```swift\nfunc application(_ application: UIApplication,\n                 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {\n    let token = deviceToken.map { String(format: \"%02x\", $0) }.joined()\n    sendTokenToServer(token)\n}\n```\n\n### Key Rules\n\n- **Never cache locally** — request fresh at every app launch via `registerForRemoteNotifications()`\n- **Sandbox ≠ production** — tokens are different per APNs environment, endpoints are different (`api.sandbox.push.apple.com` vs `api.push.apple.com`)\n- **Server sync** — send token + bundle ID + user ID + environment (sandbox\u002Fproduction) to your server\n- **Tokens change** after backup restore, device migration, reinstall, or OS updates\n\n## Notification Types Decision Tree\n\n```\nWhat type of notification?\n│\n├─ Alert (user-visible)\n│  ├─ Passive — informational, no sound, appears in history\n│  │  interruption-level: \"passive\"\n│  │\n│  ├─ Active — default, sound + banner\n│  │  interruption-level: \"active\" (or omit, it's default)\n│  │\n│  ├─ Time Sensitive — breaks through scheduled summary, not Focus\n│  │  interruption-level: \"time-sensitive\"\n│  │  Requires: Time Sensitive Notifications capability\n│  │\n│  └─ Critical — breaks through Do Not Disturb and mute switch\n│     interruption-level: \"critical\"\n│     Requires: Apple entitlement approval (medical, safety, security)\n│\n├─ Communication (iOS 15+)\n│  Shows sender avatar, name, breaks Focus for allowed contacts\n│  Requires: INSendMessageIntent + Communication Notifications capability\n│  Configured in service extension via content.updating(from: intent)\n│\n├─ Silent \u002F Background\n│  content-available: 1, no alert\u002Fsound\u002Fbadge\n│  Throttled to ~2-3 per hour\n│  apns-priority: 5 (MUST be 5, not 10)\n│  App gets ~30 seconds background execution\n│\n└─ Live Activity\n   apns-push-type: liveactivity\n   apns-topic: {bundleID}.push-type.liveactivity\n   Updates\u002Fstarts\u002Fends Live Activities remotely\n```\n\n## Payload Design Patterns\n\n### Basic Alert\n\n```json\n{\n  \"aps\": {\n    \"alert\": {\n      \"title\": \"New Message\",\n      \"subtitle\": \"From Alice\",\n      \"body\": \"Hey, are you free for lunch?\"\n    },\n    \"sound\": \"default\",\n    \"badge\": 3\n  }\n}\n```\n\n### Sound Options\n\n```json\n{\n  \"aps\": {\n    \"alert\": { \"title\": \"Notification\", \"body\": \"With custom sound\" },\n    \"sound\": \"custom-sound.aiff\"\n  }\n}\n```\n\nCritical alert (requires Apple entitlement):\n```json\n{\n  \"aps\": {\n    \"alert\": { \"title\": \"Emergency\", \"body\": \"Critical alert\" },\n    \"sound\": {\n      \"critical\": 1,\n      \"name\": \"alarm.aiff\",\n      \"volume\": 0.8\n    }\n  }\n}\n```\n\n### Badge\n\n```json\n{\n  \"aps\": {\n    \"badge\": 5\n  }\n}\n```\n\nSet to `0` to remove badge.\n\n### Localized Content\n\n```json\n{\n  \"aps\": {\n    \"alert\": {\n      \"loc-key\": \"NEW_MESSAGE_FORMAT\",\n      \"loc-args\": [\"Alice\", \"lunch\"]\n    }\n  }\n}\n```\n\n### Custom Data\n\nPlace custom data outside the `aps` dictionary:\n\n```json\n{\n  \"aps\": {\n    \"alert\": { \"title\": \"Order Update\", \"body\": \"Your order shipped\" }\n  },\n  \"orderId\": \"12345\",\n  \"deepLink\": \"\u002Forders\u002F12345\"\n}\n```\n\n### Relevance Score and Thread ID\n\n```json\n{\n  \"aps\": {\n    \"alert\": { \"title\": \"Breaking News\", \"body\": \"...\" },\n    \"relevance-score\": 0.8,\n    \"thread-id\": \"news-breaking\",\n    \"interruption-level\": \"time-sensitive\"\n  }\n}\n```\n\n- `relevance-score` (0.0–1.0): ranking for notification summary (iOS 15+)\n- `thread-id`: groups notifications into conversations in Notification Center\n\n### Payload Size Limits\n\n| Type | Max Size |\n|------|----------|\n| Standard push | 4KB |\n| VoIP push | 5KB |\n| Live Activity | 4KB |\n\nAPNs silently rejects oversized payloads. No error returned to sender.\n\n## Categories and Actions\n\n### Register Categories at Launch\n\n```swift\nfunc registerNotificationCategories() {\n    let replyAction = UNTextInputNotificationAction(\n        identifier: \"REPLY_ACTION\",\n        title: \"Reply\",\n        options: [])\n\n    \u002F\u002F iOS 15+: actions with icons\n    let likeIcon = UNNotificationActionIcon(systemImageName: \"hand.thumbsup\")\n    let likeAction = UNNotificationAction(\n        identifier: \"LIKE_ACTION\",\n        title: \"Like\",\n        options: [],\n        icon: likeIcon)\n\n    let messageCategory = UNNotificationCategory(\n        identifier: \"MESSAGE\",\n        actions: [replyAction, likeAction],\n        intentIdentifiers: [],\n        options: [.customDismissAction])\n\n    UNUserNotificationCenter.current().setNotificationCategories([messageCategory])\n}\n```\n\n### Set Category in Payload\n\n```json\n{\n  \"aps\": {\n    \"alert\": { \"title\": \"Alice\", \"body\": \"Are you free?\" },\n    \"category\": \"MESSAGE\"\n  }\n}\n```\n\n### Handle Action Response\n\n```swift\nextension AppDelegate: UNUserNotificationCenterDelegate {\n    func userNotificationCenter(_ center: UNUserNotificationCenter,\n                                didReceive response: UNNotificationResponse,\n                                withCompletionHandler completionHandler: @escaping () -> Void) {\n        let userInfo = response.notification.request.content.userInfo\n\n        switch response.actionIdentifier {\n        case \"REPLY_ACTION\":\n            if let textResponse = response as? UNTextInputNotificationResponse {\n                handleReply(text: textResponse.userText, userInfo: userInfo)\n            }\n        case \"LIKE_ACTION\":\n            handleLike(userInfo: userInfo)\n        case UNNotificationDefaultActionIdentifier:\n            \u002F\u002F User tapped the notification itself\n            handleNotificationTap(userInfo: userInfo)\n        case UNNotificationDismissActionIdentifier:\n            \u002F\u002F User dismissed (requires .customDismissAction on category)\n            handleDismiss(userInfo: userInfo)\n        default:\n            break\n        }\n\n        completionHandler()\n    }\n}\n```\n\n## Service Extension Patterns\n\n### Pattern 1: Media Enrichment\n\nDownload and attach images, audio, or video to notifications.\n\n**Payload requirement**: Must include `\"mutable-content\": 1`:\n\n```json\n{\n  \"aps\": {\n    \"alert\": { \"title\": \"Photo\", \"body\": \"Alice sent a photo\" },\n    \"mutable-content\": 1\n  },\n  \"imageURL\": \"https:\u002F\u002Fexample.com\u002Fphoto.jpg\"\n}\n```\n\n**Service extension**:\n\n```swift\nclass NotificationService: UNNotificationServiceExtension {\n    var contentHandler: ((UNNotificationContent) -> Void)?\n    var bestAttemptContent: UNMutableNotificationContent?\n\n    override func didReceive(_ request: UNNotificationRequest,\n                             withContentHandler contentHandler:\n                                @escaping (UNNotificationContent) -> Void) {\n        self.contentHandler = contentHandler\n        bestAttemptContent = request.content.mutableCopy() as? UNMutableNotificationContent\n\n        guard let bestAttemptContent,\n              let imageURLString = bestAttemptContent.userInfo[\"imageURL\"] as? String,\n              let imageURL = URL(string: imageURLString) else {\n            contentHandler(request.content)\n            return\n        }\n\n        \u002F\u002F Download image\n        let task = URLSession.shared.downloadTask(with: imageURL) { [weak self] url, _, error in\n            guard let self, let url, error == nil else {\n                contentHandler(self?.bestAttemptContent ?? request.content)\n                return\n            }\n\n            \u002F\u002F Move to tmp with proper extension\n            let tmpURL = FileManager.default.temporaryDirectory\n                .appendingPathComponent(UUID().uuidString)\n                .appendingPathExtension(\"jpg\")\n            try? FileManager.default.moveItem(at: url, to: tmpURL)\n\n            if let attachment = try? UNNotificationAttachment(identifier: \"image\",\n                                                               url: tmpURL,\n                                                               options: nil) {\n                bestAttemptContent.attachments = [attachment]\n            }\n\n            contentHandler(bestAttemptContent)\n        }\n        task.resume()\n    }\n\n    override func serviceExtensionTimeWillExpire() {\n        \u002F\u002F 30-second window exceeded — deliver what we have\n        if let contentHandler, let bestAttemptContent {\n            contentHandler(bestAttemptContent)\n        }\n    }\n}\n```\n\n### Pattern 2: End-to-End Decryption\n\nDecrypt payload in service extension before display:\n\n```swift\noverride func didReceive(_ request: UNNotificationRequest,\n                         withContentHandler contentHandler:\n                            @escaping (UNNotificationContent) -> Void) {\n    self.contentHandler = contentHandler\n    bestAttemptContent = request.content.mutableCopy() as? UNMutableNotificationContent\n\n    guard let bestAttemptContent,\n          let encryptedBody = bestAttemptContent.userInfo[\"encryptedBody\"] as? String else {\n        contentHandler(request.content)\n        return\n    }\n\n    if let decrypted = decrypt(encryptedBody) {\n        bestAttemptContent.body = decrypted\n    } else {\n        bestAttemptContent.body = \"(Encrypted message)\"\n    }\n\n    contentHandler(bestAttemptContent)\n}\n\noverride func serviceExtensionTimeWillExpire() {\n    if let contentHandler, let bestAttemptContent {\n        bestAttemptContent.body = \"(Encrypted message)\"\n        contentHandler(bestAttemptContent)\n    }\n}\n```\n\n**30-second processing window**: If `didReceive` doesn't call `contentHandler` within ~30 seconds, `serviceExtensionTimeWillExpire` is called. Always deliver `bestAttemptContent` as fallback — if neither method calls the handler, the notification vanishes entirely.\n\n## Communication Notifications (iOS 15+)\n\nShow sender avatar and name. Can break through Focus for allowed contacts.\n\n```swift\n\u002F\u002F In your Notification Service Extension\nimport Intents\n\noverride func didReceive(_ request: UNNotificationRequest,\n                         withContentHandler contentHandler:\n                            @escaping (UNNotificationContent) -> Void) {\n    guard let bestAttemptContent = request.content.mutableCopy() as? UNMutableNotificationContent else {\n        contentHandler(request.content)\n        return\n    }\n\n    \u002F\u002F 1. Create sender persona\n    let senderImage = INImage(url: avatarURL) \u002F\u002F or INImage(imageData:)\n    let sender = INPerson(\n        personHandle: INPersonHandle(value: \"alice@example.com\", type: .emailAddress),\n        nameComponents: nil,\n        displayName: \"Alice\",\n        image: senderImage,\n        contactIdentifier: nil,\n        customIdentifier: \"user-alice-123\"\n    )\n\n    \u002F\u002F 2. Create message intent\n    let intent = INSendMessageIntent(\n        recipients: nil,       \u002F\u002F nil for 1:1, set for group\n        outgoingMessageType: .outgoingMessageText,\n        content: bestAttemptContent.body,\n        speakableGroupName: nil, \u002F\u002F set for group conversations\n        conversationIdentifier: \"conversation-123\",\n        serviceName: nil,\n        sender: sender,\n        attachments: nil\n    )\n\n    \u002F\u002F 3. Donate interaction\n    let interaction = INInteraction(intent: intent, response: nil)\n    interaction.direction = .incoming\n    interaction.donate(completion: nil)\n\n    \u002F\u002F 4. Update content with intent\n    do {\n        let updatedContent = try bestAttemptContent.updating(from: intent)\n        contentHandler(updatedContent)\n    } catch {\n        contentHandler(bestAttemptContent)\n    }\n}\n```\n\n**Requirements**:\n- Communication Notifications capability in Xcode\n- Notification Service Extension target\n- `mutable-content: 1` in payload\n\n**Focus breakthrough**: Communication notifications from contacts the user has allowed in Focus settings will break through. Use sparingly — overuse erodes trust.\n\n## Foreground Notification Handling\n\nWithout this delegate method, notifications received while the app is in foreground are **silently dropped**:\n\n```swift\nextension AppDelegate: UNUserNotificationCenterDelegate {\n    func userNotificationCenter(_ center: UNUserNotificationCenter,\n                                willPresent notification: UNNotification,\n                                withCompletionHandler completionHandler:\n                                    @escaping (UNNotificationPresentationOptions) -> Void) {\n        \u002F\u002F Show notification even when app is in foreground\n        completionHandler([.banner, .sound, .badge])\n    }\n}\n```\n\nSet `UNUserNotificationCenter.current().delegate = self` in `didFinishLaunchingWithOptions` — before the app finishes launching.\n\n## Live Activity Push Transport\n\nPush updates to Live Activities remotely via APNs.\n\n### Observe Push Token\n\n```swift\nlet activity = try Activity\u003COrderAttributes>.request(\n    attributes: attributes,\n    content: initialContent,\n    pushType: .token\n)\n\nTask {\n    for await pushToken in activity.pushTokenUpdates {\n        let pushTokenString = pushToken.reduce(\"\") {\n            $0 + String(format: \"%02x\", $1)\n        }\n        try await sendPushToken(pushTokenString: pushTokenString)\n    }\n}\n```\n\n### APNs Headers for Live Activity\n\n| Header | Value |\n|--------|-------|\n| apns-push-type | `liveactivity` |\n| apns-topic | `{bundleID}.push-type.liveactivity` |\n| apns-priority | `5` (routine) or `10` (time-sensitive) |\n\n### Update Payload\n\n```json\n{\n  \"aps\": {\n    \"timestamp\": 1234567890,\n    \"event\": \"update\",\n    \"content-state\": {\n      \"currentStep\": \"outForDelivery\",\n      \"estimatedArrival\": \"2:30 PM\"\n    },\n    \"stale-date\": 1234571490,\n    \"dismissal-date\": 1234575090,\n    \"relevance-score\": 75.0\n  }\n}\n```\n\n### Event Types\n\n| Event | Purpose |\n|-------|---------|\n| `update` | Update content-state |\n| `start` | Start a new Live Activity remotely (iOS 17.2+) |\n| `end` | End the activity |\n\n### Key Rules\n\n- `content-state` **must match** `ActivityAttributes.ContentState` exactly — no custom JSON encoding strategies, property names must be identical\n- `timestamp` is required — APNs uses it to discard stale updates\n- `stale-date` shows a visual indicator that data is outdated\n- `dismissal-date` controls when an ended activity disappears from Lock Screen\n- `relevance-score` orders multiple active Live Activities\n- Priority budget enforced — excessive `apns-priority: 10` gets throttled\n- Add `NSSupportsLiveActivitiesFrequentUpdates` to Info.plist for high-frequency apps (sports, navigation)\n\nFor ActivityKit UI, attributes, and Dynamic Island layout, see axiom-extensions-widgets.\n\n## Broadcast Push (iOS 18+)\n\nChannel-based delivery for large audiences (sports scores, flight status, breaking news).\n\n### Setup\n\n1. Enable Broadcast Push Notifications capability in Apple Developer Portal\n2. Create channels via Apple's Broadcast Push API\n\n### Subscribe to Channel\n\n```swift\nlet activity = try Activity\u003CScoreAttributes>.request(\n    attributes: attributes,\n    content: initialContent,\n    pushType: .channel(channelId)\n)\n```\n\n### Server Sends to Channel\n\n```\nPOST \u002F4\u002Fbroadcasts\u002Fapps\u002F{TOPIC}\n```\n\n### Key Rules\n\n- Only available for Live Activities (not regular push)\n- Channel storage policies: **No Storage** (higher budget) vs **Most Recent Message** (stores last update)\n- Manage channel lifecycle — delete unused channels (total active channels are limited)\n- Channels are identified by opaque IDs, not user-facing names\n- More efficient than per-device token delivery for 1-to-many scenarios\n\n## FCM as Provider\n\nIf using Firebase Cloud Messaging as your push provider, watch for these gotchas:\n\n### 1. Swizzling Trap\n\nFCM swizzles `UNUserNotificationCenterDelegate` methods and `didRegisterForRemoteNotifications` by default. If you have custom delegate handling, they conflict.\n\n**Fix**: Set in Info.plist:\n```xml\n\u003Ckey>FirebaseAppDelegateProxyEnabled\u003C\u002Fkey>\n\u003Cfalse\u002F>\n```\n\nThen manually pass the APNs token to FCM:\n```swift\nfunc application(_ application: UIApplication,\n                 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {\n    Messaging.messaging().apnsToken = deviceToken\n}\n```\n\n### 2. Dual Token Confusion\n\nFCM token ≠ APNs device token. They are completely different. Send the correct one to the correct backend.\n\n- FCM token → your server (for sending via FCM)\n- APNs token → only needed if sending directly via APNs\n\n### 3. APNs Auth Key Upload\n\nUpload your .p8 APNs authentication key to Firebase Console → Project Settings → Cloud Messaging. Without this, development builds work (FCM uses sandbox automatically) but production builds silently fail.\n\n### 4. Silent Push Payload Size\n\nFCM's `content_available` maps to APNs `content-available`, but FCM may add extra fields to the payload. Monitor total size to avoid exceeding the 4KB limit.\n\n## Anti-Patterns\n\n### Anti-Pattern 1: Requesting Permission at App Launch\n\n**Wrong**:\n```swift\nfunc application(_ application: UIApplication,\n                 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {\n    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { _, _ in }\n    return true\n}\n```\n\n**Right**:\n```swift\n\u002F\u002F After user taps \"Subscribe to updates\" or completes onboarding\nfunc subscribeButtonTapped() async {\n    let granted = try? await UNUserNotificationCenter.current()\n        .requestAuthorization(options: [.alert, .sound, .badge])\n    if granted == true {\n        await MainActor.run { UIApplication.shared.registerForRemoteNotifications() }\n    }\n}\n```\n\n**Why it matters**: The system only shows the permission dialog once. If the user hasn't seen value yet, they tap \"Don't Allow\" reflexively. ~60% of users who deny never re-enable in Settings. You get one shot.\n\n### Anti-Pattern 2: Caching Device Tokens\n\n**Wrong**:\n```swift\nfunc application(_ app: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken token: Data) {\n    let tokenString = token.map { String(format: \"%02x\", $0) }.joined()\n    UserDefaults.standard.set(tokenString, forKey: \"pushToken\") \u002F\u002F Stale after restore\n}\n```\n\n**Right**:\n```swift\nfunc application(_ app: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken token: Data) {\n    let tokenString = token.map { String(format: \"%02x\", $0) }.joined()\n    sendTokenToServer(tokenString) \u002F\u002F Fresh every launch\n}\n```\n\n**Why it matters**: Tokens change after backup restore, device migration, reinstall, and sometimes after OS updates. A stale cached token means your server sends to a token APNs no longer recognizes — notifications silently vanish.\n\n### Anti-Pattern 3: Ignoring Service Extension Timeout\n\n**Wrong**:\n```swift\noverride func didReceive(_ request: UNNotificationRequest,\n                         withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {\n    \u002F\u002F Download large image, no timeout handling\n    downloadImage(from: url) { image in\n        \u002F\u002F If this takes >30 seconds, notification vanishes entirely\n        contentHandler(modifiedContent)\n    }\n}\n\u002F\u002F serviceExtensionTimeWillExpire not implemented\n```\n\n**Right**:\n```swift\noverride func serviceExtensionTimeWillExpire() {\n    if let contentHandler, let bestAttemptContent {\n        \u002F\u002F Deliver whatever we have — text without image is better than nothing\n        contentHandler(bestAttemptContent)\n    }\n}\n```\n\n**Why it matters**: The service extension has a ~30 second window. If neither `didReceive` nor `serviceExtensionTimeWillExpire` calls the content handler, the notification disappears completely. Users never see it.\n\n### Anti-Pattern 4: Using Time Sensitive for Everything\n\n**Wrong**:\n```json\n{\n  \"aps\": {\n    \"alert\": { \"title\": \"Weekly Newsletter\", \"body\": \"Check out this week's articles\" },\n    \"interruption-level\": \"time-sensitive\"\n  }\n}\n```\n\n**Right**:\n```json\n{\n  \"aps\": {\n    \"alert\": { \"title\": \"Weekly Newsletter\", \"body\": \"Check out this week's articles\" },\n    \"interruption-level\": \"passive\"\n  }\n}\n```\n\n**Why it matters**: iOS shows users which apps overuse Time Sensitive. Users who feel interrupted will disable ALL notifications from your app — not just Time Sensitive ones. Reserve it for genuinely time-bound events (delivery arriving, meeting starting, security alerts). Apple can also revoke the capability.\n\n## Pressure Scenarios\n\n### Scenario 1: \"Ship Push Notifications by Friday\"\n\n**Context**: PM needs push notifications working for a demo.\n\n**Pressure**: \"Just ask for permission at launch, we'll fix it later.\"\n\n**Reality**: The system only prompts once. If the user denies, you need them to manually enable in Settings. ~60% of users never do. \"Fix it later\" means permanently lower opt-in rates.\n\n**Correct action**:\n1. Implement push registration and delivery without the permission prompt first\n2. Add contextual permission request after a user action that makes notification value obvious\n3. Test both grant and deny flows end-to-end\n\n**Push-back template**: \"Permission timing directly affects our opt-in rate. A 2-hour investment now prevents a 30% lower notification reach permanently. Let me implement the contextual prompt — it's the same amount of code, just in the right place.\"\n\n### Scenario 2: \"Notifications Work in Dev but Not Production\"\n\n**Context**: App Store build doesn't receive push notifications.\n\n**Pressure**: \"Something is wrong with APNs, let's file a radar.\"\n\n**Reality**: 95% of the time it's a sandbox\u002Fproduction token mismatch. Dev builds use `api.sandbox.push.apple.com`, production uses `api.push.apple.com`. Tokens are different per environment. The same token sent to the wrong endpoint silently fails.\n\n**Correct action**:\n1. Verify server is using the correct APNs endpoint for the build type\n2. Check that the token was obtained from a production build (not a dev\u002FTestFlight token sent to production endpoint)\n3. If using FCM, verify the APNs authentication key (.p8) is uploaded to Firebase Console\n\n**Push-back template**: \"Before filing a radar, let me verify our token\u002Fenvironment configuration. This is the number one cause of 'works in dev, not production' and takes 5 minutes to check.\"\n\n### Scenario 3: \"Just Send Everything as Time Sensitive\"\n\n**Context**: Product wants maximum notification visibility.\n\n**Pressure**: \"Users need to see our notifications immediately.\"\n\n**Reality**: iOS shows users which apps overuse Time Sensitive. Users who feel interrupted will disable ALL notifications from your app — not just Time Sensitive. Apple can also revoke the entitlement for abuse.\n\n**Correct action**:\n1. Classify notifications by genuine urgency\n2. Use `passive` for informational, `active` (default) for normal engagement, `time-sensitive` only for truly time-bound events\n3. Document the classification for the team so backend engineers apply the right level\n\n**Push-back template**: \"Overusing Time Sensitive will cause users to disable our notifications entirely. Let's classify by urgency — most notifications should be active, with time-sensitive reserved for genuinely time-bound events like delivery arrivals or expiring offers.\"\n\n## Checklist\n\nBefore shipping push notifications:\n\n**Entitlements**:\n- ☑ Push Notifications capability added in Xcode\n- ☑ Provisioning profile includes aps-environment\n- ☑ Communication Notifications capability (if using communication type)\n\n**Permissions**:\n- ☑ Authorization requested in context (not at launch)\n- ☑ Denial handled gracefully (Settings redirect or degraded experience)\n- ☑ Authorization status checked before scheduling\n- ☑ Provisional authorization considered for trial period\n\n**Token Management**:\n- ☑ Token sent to server on every launch (never cached)\n- ☑ Server stores token per environment (sandbox\u002Fproduction)\n- ☑ Token refresh handled (pushTokenUpdates for Live Activities)\n\n**Payload**:\n- ☑ Payload under 4KB (5KB for VoIP)\n- ☑ Category identifier matches registered categories\n- ☑ Interruption level appropriate for content urgency\n- ☑ Custom data placed outside aps dictionary\n\n**Service Extension** (if applicable):\n- ☑ mutable-content: 1 set in payload\n- ☑ serviceExtensionTimeWillExpire delivers fallback content\n- ☑ App group configured for shared data access\n\n**Testing**:\n- ☑ Tested with Push Notifications Console or curl\n- ☑ Tested both foreground and background delivery\n- ☑ Tested on physical device (Simulator has no APNs token)\n\n## Resources\n\n**WWDC**: 2021-10091, 2023-10025, 2023-10185, 2024-10069\n\n**Docs**: \u002Fusernotifications, \u002Fusernotifications\u002Funusernotificationcenter, \u002Factivitykit\n\n**Skills**: axiom-push-notifications-ref, axiom-push-notifications-diag, axiom-extensions-widgets, axiom-background-processing\n\n","# Push Notifications\n\nRemote and local notification patterns for iOS. Covers permission flow, APNs registration, token management, payload design, actionable notifications, rich notifications with service extensions, communication notifications, Focus interaction, and Live Activity push transport.\n\n## When to Use This Skill\n\nUse when you need to:\n- ☑ Implementing remote (APNs) push notifications\n- ☑ Requesting notification permissions\n- ☑ Managing device tokens and server sync\n- ☑ Adding actionable notifications with categories\u002Factions\n- ☑ Building rich notifications with service extensions\n- ☑ Communication notifications with avatars (iOS 15+)\n- ☑ Time Sensitive or Critical alerts\n- ☑ Updating Live Activities via push (transport layer)\n- ☑ Broadcast push for large audiences (iOS 18+)\n- ☑ Local notification scheduling\n\n## Example Prompts\n\n\"How do I set up push notifications?\"\n\"When should I ask for notification permission?\"\n\"My push notifications aren't arriving\"\n\"How do I add buttons to notifications?\"\n\"How do I show images in push notifications?\"\n\"How do I send push updates to a Live Activity?\"\n\"What's the difference between APNs token and FCM token?\"\n\"How do I make notifications break through Focus mode?\"\n\"My notifications work in development but not production\"\n\"How do I handle notification taps to open a specific screen?\"\n\n## Red Flags\n\nSigns you're making this harder than it needs to be:\n\n- ❌ Requesting permission on first launch before user understands value\n- ❌ Caching device tokens locally instead of requesting fresh each launch\n- ❌ Sending the same token to sandbox AND production APNs\n- ❌ Using `content-available: 1` without understanding silent push throttling (~2-3\u002Fhour)\n- ❌ Not implementing `serviceExtensionTimeWillExpire` fallback\n- ❌ Force-unwrapping device token or assuming registration always succeeds\n- ❌ Hardcoding APNs host instead of switching sandbox\u002Fproduction by environment\n- ❌ Setting `apns-priority: 10` for all notifications (drains battery, gets throttled)\n- ❌ Exceeding 4KB payload without realizing APNs silently rejects it\n- ❌ Using FCM without disabling method swizzling when you have custom delegate handling\n- ❌ Not handling foreground notification presentation (notifications silently dropped)\n- ❌ Overusing Time Sensitive interruption level (erodes user trust, they'll disable all notifications)\n\n## Mandatory First Steps\n\nBefore implementing any push notification feature:\n\n### 1. Enable Push Notification Capability\n\n- Xcode: Target → Signing & Capabilities → + Push Notifications\n- Adds `aps-environment` entitlement\n- Verify in Apple Developer Portal that the App ID has Push Notifications enabled\n\n### 2. Register for Remote Notifications\n\n```swift\n\u002F\u002F AppDelegate\nfunc application(_ application: UIApplication,\n                 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {\n    UNUserNotificationCenter.current().delegate = self\n    UIApplication.shared.registerForRemoteNotifications()\n    return true\n}\n\nfunc application(_ application: UIApplication,\n                 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {\n    let token = deviceToken.map { String(format: \"%02x\", $0) }.joined()\n    sendTokenToServer(token) \u002F\u002F Never cache locally — tokens change\n}\n\nfunc application(_ application: UIApplication,\n                 didFailToRegisterForRemoteNotificationsWithError error: Error) {\n    \u002F\u002F Simulator cannot register. Log, don't crash.\n}\n```\n\n### 3. Request Authorization (in context, not at launch)\n\n```swift\nlet center = UNUserNotificationCenter.current()\nlet granted = try await center.requestAuthorization(options: [.alert, .sound, .badge])\nif granted {\n    await MainActor.run { UIApplication.shared.registerForRemoteNotifications() }\n}\n```\n\nRequest when user action makes notification value obvious (e.g., after scheduling a reminder, subscribing to updates). The system prompts only once — bad timing means permanent denial.\n\n## Permission Flow\n\n### Pattern 1: Standard Authorization\n\nRequest in context after user understands the value:\n\n```swift\nfunc subscribeToUpdates() async {\n    let center = UNUserNotificationCenter.current()\n    let settings = await center.notificationSettings()\n\n    switch settings.authorizationStatus {\n    case .notDetermined:\n        let granted = try? await center.requestAuthorization(options: [.alert, .sound, .badge])\n        if granted == true {\n            await MainActor.run { UIApplication.shared.registerForRemoteNotifications() }\n        }\n    case .authorized, .provisional:\n        \u002F\u002F Already have permission\n        break\n    case .denied:\n        \u002F\u002F Redirect to Settings\n        promptToOpenSettings()\n    case .ephemeral:\n        break\n    @unknown default:\n        break\n    }\n}\n```\n\n### Pattern 2: Provisional Authorization (iOS 12+)\n\nNotifications appear quietly in Notification Center with Keep\u002FTurn Off buttons. No permission dialog shown to user.\n\n```swift\nlet granted = try await center.requestAuthorization(options: [.alert, .sound, .badge, .provisional])\n```\n\nGood for apps where users haven't yet discovered notification value. They see notifications quietly and choose to promote them.\n\n### Pattern 3: Authorization Status Check\n\nAlways check before scheduling or assuming permission:\n\n```swift\nlet settings = await UNUserNotificationCenter.current().notificationSettings()\nguard settings.authorizationStatus == .authorized else {\n    \u002F\u002F Handle missing permission\n    return\n}\n```\n\n### Pattern 4: Handling Denial\n\nRedirect to Settings when user has denied:\n\n```swift\nfunc promptToOpenSettings() {\n    \u002F\u002F iOS 16+\n    if let url = URL(string: UIApplication.openNotificationSettingsURLString) {\n        UIApplication.shared.open(url)\n    } else {\n        \u002F\u002F Fallback: general app settings\n        if let url = URL(string: UIApplication.openSettingsURLString) {\n            UIApplication.shared.open(url)\n        }\n    }\n}\n```\n\n## Token Management\n\n### Token Format\n\n```swift\nfunc application(_ application: UIApplication,\n                 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {\n    let token = deviceToken.map { String(format: \"%02x\", $0) }.joined()\n    sendTokenToServer(token)\n}\n```\n\n### Key Rules\n\n- **Never cache locally** — request fresh at every app launch via `registerForRemoteNotifications()`\n- **Sandbox ≠ production** — tokens are different per APNs environment, endpoints are different (`api.sandbox.push.apple.com` vs `api.push.apple.com`)\n- **Server sync** — send token + bundle ID + user ID + environment (sandbox\u002Fproduction) to your server\n- **Tokens change** after backup restore, device migration, reinstall, or OS updates\n\n## Notification Types Decision Tree\n\n```\nWhat type of notification?\n│\n├─ Alert (user-visible)\n│  ├─ Passive — informational, no sound, appears in history\n│  │  interruption-level: \"passive\"\n│  │\n│  ├─ Active — default, sound + banner\n│  │  interruption-level: \"active\" (or omit, it's default)\n│  │\n│  ├─ Time Sensitive — breaks through scheduled summary, not Focus\n│  │  interruption-level: \"time-sensitive\"\n│  │  Requires: Time Sensitive Notifications capability\n│  │\n│  └─ Critical — breaks through Do Not Disturb and mute switch\n│     interruption-level: \"critical\"\n│     Requires: Apple entitlement approval (medical, safety, security)\n│\n├─ Communication (iOS 15+)\n│  Shows sender avatar, name, breaks Focus for allowed contacts\n│  Requires: INSendMessageIntent + Communication Notifications capability\n│  Configured in service extension via content.updating(from: intent)\n│\n├─ Silent \u002F Background\n│  content-available: 1, no alert\u002Fsound\u002Fbadge\n│  Throttled to ~2-3 per hour\n│  apns-priority: 5 (MUST be 5, not 10)\n│  App gets ~30 seconds background execution\n│\n└─ Live Activity\n   apns-push-type: liveactivity\n   apns-topic: {bundleID}.push-type.liveactivity\n   Updates\u002Fstarts\u002Fends Live Activities remotely\n```\n\n## Payload Design Patterns\n\n### Basic Alert\n\n```json\n{\n  \"aps\": {\n    \"alert\": {\n      \"title\": \"New Message\",\n      \"subtitle\": \"From Alice\",\n      \"body\": \"Hey, are you free for lunch?\"\n    },\n    \"sound\": \"default\",\n    \"badge\": 3\n  }\n}\n```\n\n### Sound Options\n\n```json\n{\n  \"aps\": {\n    \"alert\": { \"title\": \"Notification\", \"body\": \"With custom sound\" },\n    \"sound\": \"custom-sound.aiff\"\n  }\n}\n```\n\nCritical alert (requires Apple entitlement):\n```json\n{\n  \"aps\": {\n    \"alert\": { \"title\": \"Emergency\", \"body\": \"Critical alert\" },\n    \"sound\": {\n      \"critical\": 1,\n      \"name\": \"alarm.aiff\",\n      \"volume\": 0.8\n    }\n  }\n}\n```\n\n### Badge\n\n```json\n{\n  \"aps\": {\n    \"badge\": 5\n  }\n}\n```\n\nSet to `0` to remove badge.\n\n### Localized Content\n\n```json\n{\n  \"aps\": {\n    \"alert\": {\n      \"loc-key\": \"NEW_MESSAGE_FORMAT\",\n      \"loc-args\": [\"Alice\", \"lunch\"]\n    }\n  }\n}\n```\n\n### Custom Data\n\nPlace custom data outside the `aps` dictionary:\n\n```json\n{\n  \"aps\": {\n    \"alert\": { \"title\": \"Order Update\", \"body\": \"Your order shipped\" }\n  },\n  \"orderId\": \"12345\",\n  \"deepLink\": \"\u002Forders\u002F12345\"\n}\n```\n\n### Relevance Score and Thread ID\n\n```json\n{\n  \"aps\": {\n    \"alert\": { \"title\": \"Breaking News\", \"body\": \"...\" },\n    \"relevance-score\": 0.8,\n    \"thread-id\": \"news-breaking\",\n    \"interruption-level\": \"time-sensitive\"\n  }\n}\n```\n\n- `relevance-score` (0.0–1.0): ranking for notification summary (iOS 15+)\n- `thread-id`: groups notifications into conversations in Notification Center\n\n### Payload Size Limits\n\n| Type | Max Size |\n|------|----------|\n| Standard push | 4KB |\n| VoIP push | 5KB |\n| Live Activity | 4KB |\n\nAPNs silently rejects oversized payloads. No error returned to sender.\n\n## Categories and Actions\n\n### Register Categories at Launch\n\n```swift\nfunc registerNotificationCategories() {\n    let replyAction = UNTextInputNotificationAction(\n        identifier: \"REPLY_ACTION\",\n        title: \"Reply\",\n        options: [])\n\n    \u002F\u002F iOS 15+: actions with icons\n    let likeIcon = UNNotificationActionIcon(systemImageName: \"hand.thumbsup\")\n    let likeAction = UNNotificationAction(\n        identifier: \"LIKE_ACTION\",\n        title: \"Like\",\n        options: [],\n        icon: likeIcon)\n\n    let messageCategory = UNNotificationCategory(\n        identifier: \"MESSAGE\",\n        actions: [replyAction, likeAction],\n        intentIdentifiers: [],\n        options: [.customDismissAction])\n\n    UNUserNotificationCenter.current().setNotificationCategories([messageCategory])\n}\n```\n\n### Set Category in Payload\n\n```json\n{\n  \"aps\": {\n    \"alert\": { \"title\": \"Alice\", \"body\": \"Are you free?\" },\n    \"category\": \"MESSAGE\"\n  }\n}\n```\n\n### Handle Action Response\n\n```swift\nextension AppDelegate: UNUserNotificationCenterDelegate {\n    func userNotificationCenter(_ center: UNUserNotificationCenter,\n                                didReceive response: UNNotificationResponse,\n                                withCompletionHandler completionHandler: @escaping () -> Void) {\n        let userInfo = response.notification.request.content.userInfo\n\n        switch response.actionIdentifier {\n        case \"REPLY_ACTION\":\n            if let textResponse = response as? UNTextInputNotificationResponse {\n                handleReply(text: textResponse.userText, userInfo: userInfo)\n            }\n        case \"LIKE_ACTION\":\n            handleLike(userInfo: userInfo)\n        case UNNotificationDefaultActionIdentifier:\n            \u002F\u002F User tapped the notification itself\n            handleNotificationTap(userInfo: userInfo)\n        case UNNotificationDismissActionIdentifier:\n            \u002F\u002F User dismissed (requires .customDismissAction on category)\n            handleDismiss(userInfo: userInfo)\n        default:\n            break\n        }\n\n        completionHandler()\n    }\n}\n```\n\n## Service Extension Patterns\n\n### Pattern 1: Media Enrichment\n\nDownload and attach images, audio, or video to notifications.\n\n**Payload requirement**: Must include `\"mutable-content\": 1`:\n\n```json\n{\n  \"aps\": {\n    \"alert\": { \"title\": \"Photo\", \"body\": \"Alice sent a photo\" },\n    \"mutable-content\": 1\n  },\n  \"imageURL\": \"https:\u002F\u002Fexample.com\u002Fphoto.jpg\"\n}\n```\n\n**Service extension**:\n\n```swift\nclass NotificationService: UNNotificationServiceExtension {\n    var contentHandler: ((UNNotificationContent) -> Void)?\n    var bestAttemptContent: UNMutableNotificationContent?\n\n    override func didReceive(_ request: UNNotificationRequest,\n                             withContentHandler contentHandler:\n                                @escaping (UNNotificationContent) -> Void) {\n        self.contentHandler = contentHandler\n        bestAttemptContent = request.content.mutableCopy() as? UNMutableNotificationContent\n\n        guard let bestAttemptContent,\n              let imageURLString = bestAttemptContent.userInfo[\"imageURL\"] as? String,\n              let imageURL = URL(string: imageURLString) else {\n            contentHandler(request.content)\n            return\n        }\n\n        \u002F\u002F Download image\n        let task = URLSession.shared.downloadTask(with: imageURL) { [weak self] url, _, error in\n            guard let self, let url, error == nil else {\n                contentHandler(self?.bestAttemptContent ?? request.content)\n                return\n            }\n\n            \u002F\u002F Move to tmp with proper extension\n            let tmpURL = FileManager.default.temporaryDirectory\n                .appendingPathComponent(UUID().uuidString)\n                .appendingPathExtension(\"jpg\")\n            try? FileManager.default.moveItem(at: url, to: tmpURL)\n\n            if let attachment = try? UNNotificationAttachment(identifier: \"image\",\n                                                               url: tmpURL,\n                                                               options: nil) {\n                bestAttemptContent.attachments = [attachment]\n            }\n\n            contentHandler(bestAttemptContent)\n        }\n        task.resume()\n    }\n\n    override func serviceExtensionTimeWillExpire() {\n        \u002F\u002F 30-second window exceeded — deliver what we have\n        if let contentHandler, let bestAttemptContent {\n            contentHandler(bestAttemptContent)\n        }\n    }\n}\n```\n\n### Pattern 2: End-to-End Decryption\n\nDecrypt payload in service extension before display:\n\n```swift\noverride func didReceive(_ request: UNNotificationRequest,\n                         withContentHandler contentHandler:\n                            @escaping (UNNotificationContent) -> Void) {\n    self.contentHandler = contentHandler\n    bestAttemptContent = request.content.mutableCopy() as? UNMutableNotificationContent\n\n    guard let bestAttemptContent,\n          let encryptedBody = bestAttemptContent.userInfo[\"encryptedBody\"] as? String else {\n        contentHandler(request.content)\n        return\n    }\n\n    if let decrypted = decrypt(encryptedBody) {\n        bestAttemptContent.body = decrypted\n    } else {\n        bestAttemptContent.body = \"(Encrypted message)\"\n    }\n\n    contentHandler(bestAttemptContent)\n}\n\noverride func serviceExtensionTimeWillExpire() {\n    if let contentHandler, let bestAttemptContent {\n        bestAttemptContent.body = \"(Encrypted message)\"\n        contentHandler(bestAttemptContent)\n    }\n}\n```\n\n**30-second processing window**: If `didReceive` doesn't call `contentHandler` within ~30 seconds, `serviceExtensionTimeWillExpire` is called. Always deliver `bestAttemptContent` as fallback — if neither method calls the handler, the notification vanishes entirely.\n\n## Communication Notifications (iOS 15+)\n\nShow sender avatar and name. Can break through Focus for allowed contacts.\n\n```swift\n\u002F\u002F In your Notification Service Extension\nimport Intents\n\noverride func didReceive(_ request: UNNotificationRequest,\n                         withContentHandler contentHandler:\n                            @escaping (UNNotificationContent) -> Void) {\n    guard let bestAttemptContent = request.content.mutableCopy() as? UNMutableNotificationContent else {\n        contentHandler(request.content)\n        return\n    }\n\n    \u002F\u002F 1. Create sender persona\n    let senderImage = INImage(url: avatarURL) \u002F\u002F or INImage(imageData:)\n    let sender = INPerson(\n        personHandle: INPersonHandle(value: \"alice@example.com\", type: .emailAddress),\n        nameComponents: nil,\n        displayName: \"Alice\",\n        image: senderImage,\n        contactIdentifier: nil,\n        customIdentifier: \"user-alice-123\"\n    )\n\n    \u002F\u002F 2. Create message intent\n    let intent = INSendMessageIntent(\n        recipients: nil,       \u002F\u002F nil for 1:1, set for group\n        outgoingMessageType: .outgoingMessageText,\n        content: bestAttemptContent.body,\n        speakableGroupName: nil, \u002F\u002F set for group conversations\n        conversationIdentifier: \"conversation-123\",\n        serviceName: nil,\n        sender: sender,\n        attachments: nil\n    )\n\n    \u002F\u002F 3. Donate interaction\n    let interaction = INInteraction(intent: intent, response: nil)\n    interaction.direction = .incoming\n    interaction.donate(completion: nil)\n\n    \u002F\u002F 4. Update content with intent\n    do {\n        let updatedContent = try bestAttemptContent.updating(from: intent)\n        contentHandler(updatedContent)\n    } catch {\n        contentHandler(bestAttemptContent)\n    }\n}\n```\n\n**Requirements**:\n- Communication Notifications capability in Xcode\n- Notification Service Extension target\n- `mutable-content: 1` in payload\n\n**Focus breakthrough**: Communication notifications from contacts the user has allowed in Focus settings will break through. Use sparingly — overuse erodes trust.\n\n## Foreground Notification Handling\n\nWithout this delegate method, notifications received while the app is in foreground are **silently dropped**:\n\n```swift\nextension AppDelegate: UNUserNotificationCenterDelegate {\n    func userNotificationCenter(_ center: UNUserNotificationCenter,\n                                willPresent notification: UNNotification,\n                                withCompletionHandler completionHandler:\n                                    @escaping (UNNotificationPresentationOptions) -> Void) {\n        \u002F\u002F Show notification even when app is in foreground\n        completionHandler([.banner, .sound, .badge])\n    }\n}\n```\n\nSet `UNUserNotificationCenter.current().delegate = self` in `didFinishLaunchingWithOptions` — before the app finishes launching.\n\n## Live Activity Push Transport\n\nPush updates to Live Activities remotely via APNs.\n\n### Observe Push Token\n\n```swift\nlet activity = try Activity\u003COrderAttributes>.request(\n    attributes: attributes,\n    content: initialContent,\n    pushType: .token\n)\n\nTask {\n    for await pushToken in activity.pushTokenUpdates {\n        let pushTokenString = pushToken.reduce(\"\") {\n            $0 + String(format: \"%02x\", $1)\n        }\n        try await sendPushToken(pushTokenString: pushTokenString)\n    }\n}\n```\n\n### APNs Headers for Live Activity\n\n| Header | Value |\n|--------|-------|\n| apns-push-type | `liveactivity` |\n| apns-topic | `{bundleID}.push-type.liveactivity` |\n| apns-priority | `5` (routine) or `10` (time-sensitive) |\n\n### Update Payload\n\n```json\n{\n  \"aps\": {\n    \"timestamp\": 1234567890,\n    \"event\": \"update\",\n    \"content-state\": {\n      \"currentStep\": \"outForDelivery\",\n      \"estimatedArrival\": \"2:30 PM\"\n    },\n    \"stale-date\": 1234571490,\n    \"dismissal-date\": 1234575090,\n    \"relevance-score\": 75.0\n  }\n}\n```\n\n### Event Types\n\n| Event | Purpose |\n|-------|---------|\n| `update` | Update content-state |\n| `start` | Start a new Live Activity remotely (iOS 17.2+) |\n| `end` | End the activity |\n\n### Key Rules\n\n- `content-state` **must match** `ActivityAttributes.ContentState` exactly — no custom JSON encoding strategies, property names must be identical\n- `timestamp` is required — APNs uses it to discard stale updates\n- `stale-date` shows a visual indicator that data is outdated\n- `dismissal-date` controls when an ended activity disappears from Lock Screen\n- `relevance-score` orders multiple active Live Activities\n- Priority budget enforced — excessive `apns-priority: 10` gets throttled\n- Add `NSSupportsLiveActivitiesFrequentUpdates` to Info.plist for high-frequency apps (sports, navigation)\n\nFor ActivityKit UI, attributes, and Dynamic Island layout, see axiom-extensions-widgets.\n\n## Broadcast Push (iOS 18+)\n\nChannel-based delivery for large audiences (sports scores, flight status, breaking news).\n\n### Setup\n\n1. Enable Broadcast Push Notifications capability in Apple Developer Portal\n2. Create channels via Apple's Broadcast Push API\n\n### Subscribe to Channel\n\n```swift\nlet activity = try Activity\u003CScoreAttributes>.request(\n    attributes: attributes,\n    content: initialContent,\n    pushType: .channel(channelId)\n)\n```\n\n### Server Sends to Channel\n\n```\nPOST \u002F4\u002Fbroadcasts\u002Fapps\u002F{TOPIC}\n```\n\n### Key Rules\n\n- Only available for Live Activities (not regular push)\n- Channel storage policies: **No Storage** (higher budget) vs **Most Recent Message** (stores last update)\n- Manage channel lifecycle — delete unused channels (total active channels are limited)\n- Channels are identified by opaque IDs, not user-facing names\n- More efficient than per-device token delivery for 1-to-many scenarios\n\n## FCM as Provider\n\nIf using Firebase Cloud Messaging as your push provider, watch for these gotchas:\n\n### 1. Swizzling Trap\n\nFCM swizzles `UNUserNotificationCenterDelegate` methods and `didRegisterForRemoteNotifications` by default. If you have custom delegate handling, they conflict.\n\n**Fix**: Set in Info.plist:\n```xml\n\u003Ckey>FirebaseAppDelegateProxyEnabled\u003C\u002Fkey>\n\u003Cfalse\u002F>\n```\n\nThen manually pass the APNs token to FCM:\n```swift\nfunc application(_ application: UIApplication,\n                 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {\n    Messaging.messaging().apnsToken = deviceToken\n}\n```\n\n### 2. Dual Token Confusion\n\nFCM token ≠ APNs device token. They are completely different. Send the correct one to the correct backend.\n\n- FCM token → your server (for sending via FCM)\n- APNs token → only needed if sending directly via APNs\n\n### 3. APNs Auth Key Upload\n\nUpload your .p8 APNs authentication key to Firebase Console → Project Settings → Cloud Messaging. Without this, development builds work (FCM uses sandbox automatically) but production builds silently fail.\n\n### 4. Silent Push Payload Size\n\nFCM's `content_available` maps to APNs `content-available`, but FCM may add extra fields to the payload. Monitor total size to avoid exceeding the 4KB limit.\n\n## Anti-Patterns\n\n### Anti-Pattern 1: Requesting Permission at App Launch\n\n**Wrong**:\n```swift\nfunc application(_ application: UIApplication,\n                 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {\n    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { _, _ in }\n    return true\n}\n```\n\n**Right**:\n```swift\n\u002F\u002F After user taps \"Subscribe to updates\" or completes onboarding\nfunc subscribeButtonTapped() async {\n    let granted = try? await UNUserNotificationCenter.current()\n        .requestAuthorization(options: [.alert, .sound, .badge])\n    if granted == true {\n        await MainActor.run { UIApplication.shared.registerForRemoteNotifications() }\n    }\n}\n```\n\n**Why it matters**: The system only shows the permission dialog once. If the user hasn't seen value yet, they tap \"Don't Allow\" reflexively. ~60% of users who deny never re-enable in Settings. You get one shot.\n\n### Anti-Pattern 2: Caching Device Tokens\n\n**Wrong**:\n```swift\nfunc application(_ app: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken token: Data) {\n    let tokenString = token.map { String(format: \"%02x\", $0) }.joined()\n    UserDefaults.standard.set(tokenString, forKey: \"pushToken\") \u002F\u002F Stale after restore\n}\n```\n\n**Right**:\n```swift\nfunc application(_ app: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken token: Data) {\n    let tokenString = token.map { String(format: \"%02x\", $0) }.joined()\n    sendTokenToServer(tokenString) \u002F\u002F Fresh every launch\n}\n```\n\n**Why it matters**: Tokens change after backup restore, device migration, reinstall, and sometimes after OS updates. A stale cached token means your server sends to a token APNs no longer recognizes — notifications silently vanish.\n\n### Anti-Pattern 3: Ignoring Service Extension Timeout\n\n**Wrong**:\n```swift\noverride func didReceive(_ request: UNNotificationRequest,\n                         withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {\n    \u002F\u002F Download large image, no timeout handling\n    downloadImage(from: url) { image in\n        \u002F\u002F If this takes >30 seconds, notification vanishes entirely\n        contentHandler(modifiedContent)\n    }\n}\n\u002F\u002F serviceExtensionTimeWillExpire not implemented\n```\n\n**Right**:\n```swift\noverride func serviceExtensionTimeWillExpire() {\n    if let contentHandler, let bestAttemptContent {\n        \u002F\u002F Deliver whatever we have — text without image is better than nothing\n        contentHandler(bestAttemptContent)\n    }\n}\n```\n\n**Why it matters**: The service extension has a ~30 second window. If neither `didReceive` nor `serviceExtensionTimeWillExpire` calls the content handler, the notification disappears completely. Users never see it.\n\n### Anti-Pattern 4: Using Time Sensitive for Everything\n\n**Wrong**:\n```json\n{\n  \"aps\": {\n    \"alert\": { \"title\": \"Weekly Newsletter\", \"body\": \"Check out this week's articles\" },\n    \"interruption-level\": \"time-sensitive\"\n  }\n}\n```\n\n**Right**:\n```json\n{\n  \"aps\": {\n    \"alert\": { \"title\": \"Weekly Newsletter\", \"body\": \"Check out this week's articles\" },\n    \"interruption-level\": \"passive\"\n  }\n}\n```\n\n**Why it matters**: iOS shows users which apps overuse Time Sensitive. Users who feel interrupted will disable ALL notifications from your app — not just Time Sensitive ones. Reserve it for genuinely time-bound events (delivery arriving, meeting starting, security alerts). Apple can also revoke the capability.\n\n## Pressure Scenarios\n\n### Scenario 1: \"Ship Push Notifications by Friday\"\n\n**Context**: PM needs push notifications working for a demo.\n\n**Pressure**: \"Just ask for permission at launch, we'll fix it later.\"\n\n**Reality**: The system only prompts once. If the user denies, you need them to manually enable in Settings. ~60% of users never do. \"Fix it later\" means permanently lower opt-in rates.\n\n**Correct action**:\n1. Implement push registration and delivery without the permission prompt first\n2. Add contextual permission request after a user action that makes notification value obvious\n3. Test both grant and deny flows end-to-end\n\n**Push-back template**: \"Permission timing directly affects our opt-in rate. A 2-hour investment now prevents a 30% lower notification reach permanently. Let me implement the contextual prompt — it's the same amount of code, just in the right place.\"\n\n### Scenario 2: \"Notifications Work in Dev but Not Production\"\n\n**Context**: App Store build doesn't receive push notifications.\n\n**Pressure**: \"Something is wrong with APNs, let's file a radar.\"\n\n**Reality**: 95% of the time it's a sandbox\u002Fproduction token mismatch. Dev builds use `api.sandbox.push.apple.com`, production uses `api.push.apple.com`. Tokens are different per environment. The same token sent to the wrong endpoint silently fails.\n\n**Correct action**:\n1. Verify server is using the correct APNs endpoint for the build type\n2. Check that the token was obtained from a production build (not a dev\u002FTestFlight token sent to production endpoint)\n3. If using FCM, verify the APNs authentication key (.p8) is uploaded to Firebase Console\n\n**Push-back template**: \"Before filing a radar, let me verify our token\u002Fenvironment configuration. This is the number one cause of 'works in dev, not production' and takes 5 minutes to check.\"\n\n### Scenario 3: \"Just Send Everything as Time Sensitive\"\n\n**Context**: Product wants maximum notification visibility.\n\n**Pressure**: \"Users need to see our notifications immediately.\"\n\n**Reality**: iOS shows users which apps overuse Time Sensitive. Users who feel interrupted will disable ALL notifications from your app — not just Time Sensitive. Apple can also revoke the entitlement for abuse.\n\n**Correct action**:\n1. Classify notifications by genuine urgency\n2. Use `passive` for informational, `active` (default) for normal engagement, `time-sensitive` only for truly time-bound events\n3. Document the classification for the team so backend engineers apply the right level\n\n**Push-back template**: \"Overusing Time Sensitive will cause users to disable our notifications entirely. Let's classify by urgency — most notifications should be active, with time-sensitive reserved for genuinely time-bound events like delivery arrivals or expiring offers.\"\n\n## Checklist\n\nBefore shipping push notifications:\n\n**Entitlements**:\n- ☑ Push Notifications capability added in Xcode\n- ☑ Provisioning profile includes aps-environment\n- ☑ Communication Notifications capability (if using communication type)\n\n**Permissions**:\n- ☑ Authorization requested in context (not at launch)\n- ☑ Denial handled gracefully (Settings redirect or degraded experience)\n- ☑ Authorization status checked before scheduling\n- ☑ Provisional authorization considered for trial period\n\n**Token Management**:\n- ☑ Token sent to server on every launch (never cached)\n- ☑ Server stores token per environment (sandbox\u002Fproduction)\n- ☑ Token refresh handled (pushTokenUpdates for Live Activities)\n\n**Payload**:\n- ☑ Payload under 4KB (5KB for VoIP)\n- ☑ Category identifier matches registered categories\n- ☑ Interruption level appropriate for content urgency\n- ☑ Custom data placed outside aps dictionary\n\n**Service Extension** (if applicable):\n- ☑ mutable-content: 1 set in payload\n- ☑ serviceExtensionTimeWillExpire delivers fallback content\n- ☑ App group configured for shared data access\n\n**Testing**:\n- ☑ Tested with Push Notifications Console or curl\n- ☑ Tested both foreground and background delivery\n- ☑ Tested on physical device (Simulator has no APNs token)\n\n## Resources\n\n**WWDC**: 2021-10091, 2023-10025, 2023-10185, 2024-10069\n\n**Docs**: \u002Fusernotifications, \u002Fusernotifications\u002Funusernotificationcenter, \u002Factivitykit\n\n**Skills**: axiom-push-notifications-ref, axiom-push-notifications-diag, axiom-extensions-widgets, axiom-background-processing\n\n",{"name":5,"license":15,"description":7},"main","def8531e65114c0fca8fb8551c1871ee0eed705c","skills\u002FCharlesWiltgen\u002FAxiom\u002Faxiom-push-notifications",24,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub","https:\u002F\u002Fskillshub.wtf","https:\u002F\u002Fgithub.com\u002FComeOnOliver","AI & Blockchain Engineer\r\n","2026-06-24 22:07:19",{"source":8,"skillName":5,"commands":52,"prompt":62,"zipAvailable":63},[53,56,59],{"tool":54,"command":55},"npx","npx skills add ComeOnOliver\u002Fskillshub --skill axiom-push-notifications",{"tool":57,"command":58},"bunx","bunx skills add ComeOnOliver\u002Fskillshub --skill axiom-push-notifications",{"tool":60,"command":61},"pnpm","pnpm dlx skills add ComeOnOliver\u002Fskillshub --skill axiom-push-notifications","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002FCharlesWiltgen\u002FAxiom\u002Faxiom-push-notifications\u002FSKILL.md",true,[],[66,75,84,93,99,105],{"skillNo":67,"name":68,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":37},"01M6FKJN13GMG4KY57J3QD8GY5","model-hierarchy-skill","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzscole\u002Fmodel-hierarchy-skill\u002Fmodel-hierarchy-skill\u002FSKILL.md",[],[72,73,74],"model","model hierarchy","model hierarchy skill",{"skillNo":76,"name":77,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":37},"01M6FKJJJ6GCAMR4PPPRD12M5X","zoom-mcp","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-mcp\u002FSKILL.md",[],[81,82,83],"MCP","zoom","zoom mcp",{"skillNo":85,"name":86,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":37},"01M6FKJE3KYT3KPEZMEEHYKA6K","zoom-apps-sdk","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-apps-sdk\u002FSKILL.md",[],[90,91,92,82],"sdk","zoom apps sdk","apps",{"skillNo":94,"name":95,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":37},"01M6FKJ9EDH9Q5VWDF8HAJRSP0","windows","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwindows\u002FSKILL.md",[],[95],{"skillNo":100,"name":101,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":37},"01M6FKJ666BEEFC3AE9GJ72Q93","whiteboard","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwhiteboard\u002FSKILL.md",[],[101],{"skillNo":106,"name":107,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":37},"01M6FKJ21WFCDGTJQ2Q91T9DVW","websockets","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwebsockets\u002FSKILL.md",[],[107]]