<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Saad Sherif on Medium]]></title>
        <description><![CDATA[Stories by Saad Sherif on Medium]]></description>
        <link>https://medium.com/@saadsherif02?source=rss-272a2ec2e25d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KlL3XyoSOqPzxEXBmnUfoA@2x.jpeg</url>
            <title>Stories by Saad Sherif on Medium</title>
            <link>https://medium.com/@saadsherif02?source=rss-272a2ec2e25d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:36:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saadsherif02/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[iOS Notifications, End to End — Appendix: Cheat Sheet and Release Checklist]]></title>
            <link>https://medium.com/@saadsherif02/ios-notifications-end-to-end-appendix-cheat-sheet-and-release-checklist-f167f28fe731?source=rss-272a2ec2e25d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f167f28fe731</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Saad Sherif]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 15:18:00 GMT</pubDate>
            <atom:updated>2026-09-27T15:19:17.922Z</atom:updated>
            <content:encoded><![CDATA[<p><em>One page to bookmark: every limit, payload key, header and error code from the series, the commands that test them, a plain-words glossary, and the checklist to run before you ship.</em></p><p><em>This is the appendix of </em><a href="https://medium.com/@saadsherif02/ios-notifications-end-to-end-part-0-which-notification-do-you-need-cf3057ad7b9e"><em>iOS Notifications, End to End</em></a><em>. New to the series? Start with Part 0, the map.</em></p><p>This page collects everything from Parts 0 to 7 that you’ll want to look up again. Where Apple’s documentation and my own tests disagreed, it says so. The rule I followed throughout: follow the docs, and know what the servers actually do.</p><blockquote><em>Everything this page refers to is in the </em><a href="https://github.com/Sa3doola/NotifyLab"><em>NotifyLab repo</em></a><em>.</em></blockquote><h3>Limits</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L6qcdF72Yl8yr94Yjj-j-A.png" /><figcaption><em>Every number the series relies on. The payload row is the only place my tests and Apple’s docs disagreed.</em></figcaption></figure><h3>The payload</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AW0zd9WKNPPzA0my_K80kw.png" /><figcaption><em>What goes in a payload. Apple reads </em><em>aps; everything outside it is yours.</em></figcaption></figure><h3>The headers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HD2PaYyyAWcPVYp-SswOIA.png" /><figcaption><em>The six request headers (Part 4). VoIP pushes use </em><em>voip, topic </em><em>&lt;bundle ID&gt;.voip, priority 10 and expiration 0 (Part 6).</em></figcaption></figure><p>The response brings two more: apns-id (yours, or one APNs made up), and in the sandbox only apns-unique-id, which you paste into the Delivery Log (Part 7).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IBjyXOg-59UQtVI55QfMxw.png" /><figcaption><em>Every error the series met. The reasons in bold are ones I triggered myself while writing it; the rest come from Apple’s and Firebase’s documentation.</em></figcaption></figure><p>The rule of thumb for your server: retry 429, 500 and 503 with backoff; delete the token on 410 and FCM&#39;s 404; fix the request for everything else. Never delete a token on 400 BadDeviceToken. It usually means the wrong environment, not a dead token.</p><h3>What works where</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D_efp8XizYFdDGwuN3jHBw.png" /><figcaption><em>Test layout on the Simulator, and everything else on a device (Part 7).</em></figcaption></figure><h3>The commands</h3><p>Everything runs from the NotifyLab/ folder. Variables set in the shell override tools/.env.</p><pre>node tools/check-key.mjs                                   # is my key right? no device needed<br>./tools/apns.sh payloads/order-shipped.apns                # alert, priority 10<br>COLLAPSE_ID=order-1042 ./tools/apns.sh payloads/order-out-for-delivery.apns<br>EXPIRATION=0 ./tools/apns.sh payloads/order-shipped.apns   # try once, don&#39;t store<br>./tools/apns.sh payloads/marketing-passive.apns marketing  # passive, priority 5<br>./tools/apns.sh payloads/silent-sync.apns background       # silent, priority 5<br>./tools/apns.sh payloads/driver-message.apns               # communication notification<br>./tools/apns.sh payloads/voip-call.json voip               # PushKit → CallKit, on a device<br>node tools/fcm.mjs payloads/order-shipped.apns             # the same, through FCM HTTP v1<br>node tools/jwt.mjs                                         # a JWT for Postman, valid for an hour<br>node tools/registry-server.mjs                             # the demo token server, port 8080<br>xcrun simctl push booted payloads/order-shipped.apns       # Simulator only: no key, no server<br>./tools/set-bundle-prefix.sh com.yourname                  # switch every ID to yours</pre><h3>Release checklist</h3><p>Run through this before the first release, and again whenever you change signing, keys or your push server. The part in brackets explains each item.</p><p>In the app</p><ul><li>The exported build says aps-environment → production. Check it with codesign on the .app inside the .ipa. (Part 2)</li><li>The App ID has every capability you use: Push Notifications, Time Sensitive, Communication Notifications, and App Groups for the app and both extensions. (Part 2)</li><li>The extensions’ minimum iOS version isn’t newer than the app’s. (Part 5)</li><li>The notification delegate is set, and categories are registered, before didFinishLaunching returns. (Part 1)</li><li>willPresent returns what the app should show when it&#39;s open. (Part 1)</li><li>Permission is asked next to the feature, not at launch. A denial leads to a deep link to Settings, not another prompt. (Part 1)</li><li>Local reminders stay under 64 pending, with a rolling window. (Part 1)</li><li>registerForRemoteNotifications() runs on every launch. Tokens are uploaded when they change, plus a weekly check-in. (Part 3)</li><li>The app syncs on launch, and doesn’t rely on silent pushes alone. (Part 4)</li><li>The Service Extension always calls its content handler, and falls back in serviceExtensionTimeWillExpire(). (Part 5)</li><li>Every VoIP push reports a call to CallKit, first. CallKit is off for users in mainland China, with a fallback. (Part 6)</li><li>Images, silent pushes and calls were tested on a real device, in both a Debug and a TestFlight build. (Part 7)</li></ul><p>On your server</p><ul><li>The .p8 lives in a secret manager. There&#39;s one key per environment, and a plan to rotate: new key first, then revoke the old one. (Part 2)</li><li>The JWT is cached and reused for 20 to 60 minutes. (Part 2)</li><li>Requests use HTTP/2 over reused connections. The trust store includes <em>USERTrust RSA Certification Authority</em>. (Parts 2, 4)</li><li>Every token is stored with its environment, and sent to the matching APNs host. (Parts 2, 3)</li><li>Dead tokens are deleted on 410 and FCM&#39;s 404, and silent devices are pruned. (Part 3)</li><li>One row per device, not per user. Logging out detaches the device from the user. (Part 3)</li><li>Order-style updates use collapse IDs. Anything that goes stale has an expiration. (Part 4)</li><li>Priority 10 only for what the user needs now; 5 for marketing and silent pushes. (Part 4)</li><li>Payloads stay under 4 KB and carry IDs, not personal data. (Part 4)</li><li>Marketing pushes need their own in-app opt-in, and an in-app opt-out, checked before every send (App Review Guideline 4.5.4). (Part 4)</li><li>Every send logs its apns-id, status and environment. Opens are counted by the app. (Part 7)</li></ul><p>If you use Firebase</p><ul><li>The .p8 is uploaded to both the development and production slots. (Part 3)</li><li>GoogleService-Info.plist comes from the right Firebase project. (Part 3)</li><li>If swizzling is off, the app passes the APNs token to Messaging.messaging().apnsToken. (Part 3)</li><li>The server uses FCM HTTP v1. The legacy API is gone. (Part 4)</li></ul><h3>Glossary</h3><ul><li>APNs: Apple Push Notification service, the servers that deliver every remote push to Apple devices.</li><li>Device token: the address of one app, on one device, in one environment. No fixed length. (Part 3)</li><li>FCM token: Firebase’s address for the same app, built from the APNs token. (Part 3)</li><li>VoIP token: a separate address for calls, from PushKit. (Part 6)</li><li>Sandbox / production: APNs’s two environments. Debug builds use sandbox; TestFlight and the App Store use production. (Part 2)</li><li>Topic: the bundle ID a push is for, sent as apns-topic. (Part 2)</li><li>Capability: a feature you switch on for a target in Xcode, like Push Notifications. (Part 2)</li><li>Entitlement: the signed permission a capability becomes, like aps-environment. (Part 2)</li><li>Provisioning profile: Apple’s file that says which entitlements your signed app may use. (Part 2)</li><li>.p8 key: the file your server uses to prove it&#39;s allowed to send pushes for your team. (Part 2)</li><li>JWT: the short, signed token your server makes from the .p8 and sends with each request. (Part 2)</li><li>Category: a named set of buttons for a notification. (Part 1)</li><li>Interruption level: how loud a notification is allowed to be: passive, active, time-sensitive or critical. (Parts 1, 7)</li><li>Thread ID: groups notifications together. Collapse ID: replaces an older one with a newer one. (Part 4)</li><li>Silent push: a push with nothing to show that wakes the app in the background. (Part 4)</li><li>Service Extension: your code that changes a notification before it’s shown. (Part 5)</li><li>Content Extension: your UI shown when the user long-presses a notification. (Part 5)</li><li>Communication notification: a notification shown as a message from a person, with their photo. (Part 5)</li><li>PushKit / CallKit: the frameworks that receive VoIP pushes and show the system call screen. (Part 6)</li><li>Focus / Scheduled Summary: the user’s filters for who may interrupt them, and when. (Part 7)</li><li>Delivery Log: Apple’s web tool that shows whether a sandbox push reached the device. (Part 7)</li></ul><p>That’s the series. If a notification still doesn’t arrive, start at the top of Part 7’s seven checks and go down until one fails. It’s almost always one of them.</p><p>Back to the start: <a href="https://medium.com/@saadsherif02/ios-notifications-end-to-end-part-0-which-notification-do-you-need-cf3057ad7b9e?sharedUserId=saadsherif02">Part 0</a>, Which notification do you need?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f167f28fe731" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Notifications, End to End — Part 7: Real-World Delivery]]></title>
            <link>https://medium.com/@saadsherif02/ios-notifications-end-to-end-part-7-real-world-delivery-70b996fd32b6?source=rss-272a2ec2e25d------2</link>
            <guid isPermaLink="false">https://medium.com/p/70b996fd32b6</guid>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Saad Sherif]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 15:05:44 GMT</pubDate>
            <atom:updated>2026-09-27T15:18:28.080Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Why a push that APNs accepted never showed up: the seven checks between “sent” and “seen”, Focus and the Scheduled Summary, Low Power Mode, offline phones, and every tool that shows you where a notification stopped.</em></p><p><em>This is Part 7 of </em><a href="https://medium.com/@saadsherif02/ios-notifications-end-to-end-part-0-which-notification-do-you-need-cf3057ad7b9e"><em>iOS Notifications, End to End</em></a><em>. New to the series? Start with Part 0, the map.</em></p><p>Part 0 started with the most common notification problem: the notification never shows up. Every part since then built one piece of the path. This one is about the moment it breaks anyway. APNs said 200, your logs look fine, and the user says <em>&quot;I never got it.&quot;</em></p><p>A 200 only means APNs accepted the request. Between that and a banner on the screen are seven checks, some on Apple&#39;s servers and most on the phone. Each one can hold a notification back, delay it, or show it quietly, and none of them tells your server.</p><p>By the end you’ll be able to:</p><ul><li>Name the seven checks, and which of them your code controls</li><li>Predict what Focus, the Scheduled Summary and Low Power Mode will do to each kind of push</li><li>Use every testing tool, from dragging a file onto the Simulator to Apple’s Delivery Log</li><li>Walk a missing notification back to the exact check that stopped it</li></ul><blockquote><em>Code: </em><em>StatusView.swift and </em><em>NotificationPermission.swift in the </em><a href="https://github.com/Sa3doola/NotifyLab"><em>NotifyLab repo</em></a><em>. The Status tab shows most of what this part talks about, live.</em></blockquote><h3>Seven checks between “sent” and “seen”</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y3FpjefF8ebxIS0qXqa5hQ.png" /><figcaption><em>Figure 7: the seven checks, in the order a push meets them.</em></figcaption></figure><p>The first check happens on your server, the second on Apple’s, and the other five on the phone. Parts 2 to 6 covered most of them in passing. Here they are in one place:</p><ol><li>Your server → APNs or FCM. A 400, 403, 410, 413 or 429 means it never left. Part 2&#39;s error table and Part 3&#39;s cleanup handle these.</li><li>The phone is offline. APNs keeps one notification per app while the phone is off, usually the newest, until apns-expiration (at most 30 days). Five order updates sent overnight become one in the morning. With collapse IDs (Part 4) that&#39;s what you want. For a chat app, it means the app must fetch missed messages when it opens.</li><li>Power and priority. Priority 5 pushes are delivered when it suits the battery, and Low Power Mode makes iOS more careful still. The Delivery Log (below) tells you when APNs held a push back for the device’s power state.</li><li>The app’s state. Silent pushes only. A force-quit app, Background App Refresh switched off, or a used-up background budget, and the silent push never wakes the app (Part 4).</li><li>Permission. Denied means nothing shows. Provisional means Notification Center only. And even “allowed” is several separate switches the user can flip: banners, sounds, lock screen, previews and more.</li><li>Focus and the Scheduled Summary. The notification arrives, and iOS keeps it quiet or saves it for later. The next section is about this one.</li><li>The app is open. Without willPresent, nothing shows at all (Part 1).</li></ol><p>Checks 3 to 7 are the ones your server can’t see. NotifyLab’s Status tab reads them from the device:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dILuGFa1kZV7SOCHfSv0eA.png" /><figcaption><em>The Status tab re-reads all of this every time the app becomes active, and when Low Power Mode changes.</em></figcaption></figure><p><em>Critical Alerts: Not supported</em> is the honest answer here: critical alerts need an entitlement Apple grants on request, and NotifyLab doesn’t have one.</p><h3>Interruption levels, Focus and the Scheduled Summary</h3><p>Part 1 introduced interruption levels. Here’s the full picture, including what each one needs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MOKA-xY5Y5XsLkrcuFkIpQ.png" /><figcaption><em>Figure 6: pick the lowest level that still does the job.</em></figcaption></figure><p>Focus (Do Not Disturb, Sleep, Work…) is the user’s filter, not yours. In each Focus the user picks which people and apps may notify them, and whether time-sensitive notifications may break through. So:</p><ul><li>An active notification from an app the user didn’t allow waits quietly in Notification Center until the Focus ends.</li><li>A time-sensitive one gets through, if the user left <em>Time Sensitive Notifications</em> on for that Focus. They can turn it off, per Focus and per app.</li><li>A communication notification (Part 5) gets through if the <em>person</em> is allowed in that Focus.</li><li>A critical alert gets through everything, with sound, even on silent. That’s why Apple approves the entitlement by hand, for things like medical and home-safety alarms.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FhzcfgSFMdKqgH-4h2icBw.png" /><figcaption><em>Do Not Disturb with no apps allowed, and time-sensitive notifications let through. iOS describes the rule in its own words under the switch.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ItslxH6TmI17ZL0kAViGAQ.png" /><figcaption><em>The same Focus, a moment later: NotifyLab isn’t on the allowed list, but its time-sensitive order update lit up the lock screen anyway.</em></figcaption></figure><p>The Scheduled Summary is a digest the user sets up: notifications from the apps they choose are held and delivered together, at the times they pick. Time-sensitive notifications and communication notifications skip it and arrive right away. Inside the summary, iOS sorts by relevance-score (0 to 1), which is why NotifyLab&#39;s marketing push says 0.2 and the out-for-delivery push says 1.0.</p><p>Two practical rules follow:</p><ul><li>Earn “time-sensitive”. Users can switch it off for your app in one tap, and once they have, your genuinely urgent pushes wait like everything else. The Status tab’s <em>Time Sensitive</em> row tells you if they did.</li><li>Don’t fight the filters. Apps can also adapt their <em>content</em> to a Focus with Focus filters (an App Intents feature), but they can’t get around the user’s choice of who may interrupt them.</li></ul><h3>Low Power Mode, and phones that are off</h3><p>Low Power Mode cuts background work. Silent pushes can wait until later, and priority-5 pushes can be held back. A priority-10 alert the user needs now still comes through. NotifyLab’s Status tab shows the current state, and updates it the moment the user switches Low Power Mode on or off.</p><p>Background App Refresh, when switched off for your app, means silent pushes don’t wake it at all. The Status tab says so in plain words: <em>“Off (silent pushes won’t wake the app)”</em>.</p><p>An offline phone gets one notification per app when it comes back, usually the newest, and only if apns-expiration hasn&#39;t passed. Design for it: make every notification make sense on its own, collapse state updates, and let the app fetch what it missed.</p><h3>The testing toolkit</h3><p>No single tool tests everything. Here’s what each one can and can’t do, from what I measured with Xcode 27 and iOS 27:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D_efp8XizYFdDGwuN3jHBw.png" /><figcaption><em>Every tool, and where it stops. The iPhone row is the only one with no caveats.</em></figcaption></figure><h3>1. Drag and drop, or simctl push</h3><p>The fastest loop. Drag any file from payloads/ onto the Simulator window, or:</p><pre>xcrun simctl push booted payloads/order-shipped.apns</pre><p>It needs no account, key or server, which makes it perfect for checking text, buttons, grouping and deep links. The &quot;Simulator Target Bundle&quot; key in each payload tells the Simulator which app it&#39;s for, so you don&#39;t have to type the bundle ID. The limits are real, though. It never runs the Service Extension, it refuses silent payloads (<em>&quot;no user visible content&quot;</em>), and before the user allows notifications it fails with <em>&quot;Source is not authorized&quot;</em>.</p><h3>2. A real sandbox push to the Simulator</h3><p>Since Xcode 14 on Apple silicon (or T2) Macs, the Simulator gets a real APNs token, so tools/apns.sh works against it. This path doesrun the Service Extension. It still can&#39;t draw thumbnails, and silent and VoIP pushes stop short: APNs accepts them, but the silent one doesn&#39;t wake the app, and CallKit ends the call at once.</p><p>It’s also not a guaranteed channel. While writing this part, three pushes in a row got 200 from APNs and never reached the Simulator: apsd logged nothing, and neither did the app. The same payload had arrived ten minutes earlier. I never found out why. The Delivery Log would have been my next step, which is exactly what this part is about.</p><h3>3. A real iPhone</h3><p>The only complete test. Everything in this series that says “verified” was verified here: images, the order card, silent wake-ups, the driver’s photo, the ringing call.</p><h3>4. curl and Postman</h3><p>tools/apns.sh <em>is</em> the curl version (Part 4). For people who prefer a GUI, tools/NotifyLab.postman_collection.json has the same requests: three APNs sends (order, marketing, silent) and one through FCM. Two things to set up:</p><ul><li>HTTP/2. APNs refuses HTTP/1.1. In Postman, set the request’s HTTP version to HTTP/2 in its Settings.</li><li>The JWT. Run node tools/jwt.mjs and paste the result into the collection&#39;s jwt variable. It stays valid for an hour (Part 2).</li></ul><h3>5. The Push Notifications Console</h3><p>Apple’s browser tool at icloud.developer.apple.com → Push Notifications, also one click away from the Push Notifications capability in Xcode. The Send tab is a form for every header in Part 4:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n-7YLAayX0t26k9Hsvq2UQ.png" /><figcaption><em>The Console’s Send form. “Get cURL Command” turns the form into a curl request, like the one </em><em>apns.sh makes.</em></figcaption></figure><p>It’s handy for a quick check from a machine without your tools, and for showing a teammate exactly which headers matter.</p><h3>6. The Delivery Log</h3><p>This is the tool that answers <em>“did Apple deliver it?”</em>. Every sandbox response includes an apns-unique-id header (Part 2&#39;s apns.sh prints it). Paste it into the Console&#39;s Delivery Log tab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H1wn6Wj-bHP8fhqGSg5oWA.png" /><figcaption><em>The silent push from Part 4: APNs received it, and delivered it to my iPhone 316 milliseconds later.</em></figcaption></figure><p>If the log says <em>delivered</em> and the user saw nothing, the problem is on the phone: checks 4 to 7. If it never says delivered, the push is stuck before the phone (offline, or held back), and the log shows how far it got. The catch: it only works for the development environment. For production pushes, your own logs of apns-id and status are all you have.</p><h3>7. Firebase “Send test message”</h3><p>In the Firebase console, Messaging → New campaign → Notifications, write a title and text, then Send test message and paste an FCM token. If that arrives and your server’s sends don’t, the problem is in your server. If it doesn’t arrive either, check the APNs key uploaded to Firebase (Part 3).</p><h3>8. The phone’s own logs</h3><p>When nothing else explains it, ask the phone. Pushes arrive through a system process called apsd. On the Simulator you can watch it live:</p><pre>xcrun simctl spawn booted log stream --level debug --predicate &#39;process == &quot;apsd&quot;&#39; | grep &quot;Received message for&quot;</pre><p>When a push for your app arrives, you’ll see a line like this (shortened):</p><pre>apsd: Received message for enabled topic &#39;com.yourco.notifylab&#39; … with payload &#39;{&quot;aps&quot;:{…}}&#39;</pre><p>For an iPhone, open Console.app on your Mac, select the iPhone in the sidebar, click Start, and search for apsd plus your bundle ID. And NotifyLab&#39;s own event log (Status tab) shows what the app and its extensions did with the push once it arrived.</p><h3>Test it: walk a missing notification back</h3><p>When a push “didn’t arrive”, go through the checks in order, and stop at the first one that fails:</p><ol><li>Send it yourself with ./tools/apns.sh. Note the status and the apns-unique-id.</li><li>Not 200? It never left your server. Use Part 2&#39;s error table.</li><li>200? Paste the apns-unique-id into the Delivery Log. Not delivered: the phone was offline, or APNs held it back for power (check 2 or 3).</li><li>Delivered, but nothing on screen? Open NotifyLab’s Status tab. Is it allowed? Are banners on? Is <em>Time Sensitive</em> off? Is the app in the Scheduled Summary?</li><li>Is a Focus on? Check whether NotifyLab is allowed in it, and whether time-sensitive notifications may break through.</li><li>Was the app open? The event log says <em>Arrived in foreground</em> if willPresent ran.</li><li>A silent push? Check Low Power Mode, Background App Refresh, and whether the app was swiped away.</li></ol><p>Then try the filters on purpose, so you’ve seen each one once:</p><ul><li>Focus. Turn on a Focus that doesn’t allow NotifyLab but allows time-sensitive notifications. Send order-shipped.apns (active) and order-out-for-delivery.apns (time-sensitive), with the phone locked. Only the second should interrupt you. When I ran it under Do Not Disturb, the out-for-delivery push lit up the lock screen with its <em>Time Sensitive</em> label (the screenshot above). Lock the phone first: my first try at the shipped push arrived while NotifyLab was open, and then willPresent decides, not the Focus.</li><li>Scheduled Summary. Add NotifyLab to the Scheduled Summary, and send the same two. The shipped update should wait for the summary; the out-for-delivery one shouldn’t.</li><li>Offline. Turn on Airplane Mode, send three order updates, then turn it off. Only one should arrive, usually the last.</li></ul><h3>Production notes</h3><ul><li>Log every send. Store the apns-id, the status, the environment and a short hash of the token. When a user complains, that&#39;s the only trace of a production push you&#39;ll have.</li><li>Measure what you can. APNs never tells you a notification was <em>shown</em>. Count opens yourself: when the user taps, the app reports it.</li><li>Keep time-sensitive for time-sensitive things. Users turn it off for the whole app, and then nothing you send breaks through.</li><li>Design every notification to stand alone. Offline phones get only the newest; Focus and the Summary reorder the rest. Collapse state updates, expire stale news, and fetch the real state on launch.</li><li>Keep one test device per environment. A Debug build tests sandbox; a TestFlight build tests the production path your users are on.</li><li>Don’t debug on the Simulator alone. It’s great for layout and logic, and it lies about images, silent pushes and calls.</li></ul><p>Next: the <a href="https://medium.com/@saadsherif02/ios-notifications-end-to-end-appendix-cheat-sheet-and-release-checklist-f167f28fe731">appendix</a>. One page to bookmark: every limit, header and error code from this series, and the checklist to run before you ship.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70b996fd32b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Notifications, End to End — Part 6: VoIP Calls]]></title>
            <link>https://medium.com/@saadsherif02/ios-notifications-end-to-end-part-6-voip-calls-fdcde506600f?source=rss-272a2ec2e25d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdcde506600f</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[push-notification]]></category>
            <dc:creator><![CDATA[Saad Sherif]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 14:47:44 GMT</pubDate>
            <atom:updated>2026-09-27T15:06:12.380Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Make the phone ring on a locked screen, even when the app isn’t running: PushKit and its separate token, the CallKit rule iOS enforces by ending your app, and what to send when the call is missed.</em></p><p><em>This is Part 6 of </em><a href="https://medium.com/@saadsherif02/ios-notifications-end-to-end-part-0-which-notification-do-you-need-cf3057ad7b9e"><em>iOS Notifications, End to End</em></a><em>. New to the series? Start with Part 0, the map.</em></p><p>A VoIP push is the most powerful push iOS has. It needs no permission, it wakes your app right away, and it launches the app if it isn’t running. Apple attached one strict condition to that power: every VoIP push must become a visible incoming call. Break the rule and iOS ends your app on the spot.</p><p>We’re building NotifyLab’s Calls tab. By the end you’ll have:</p><ul><li>A second, separate token for calls, uploaded next to the others</li><li>A VoIP push that shows the full-screen system call UI on a locked iPhone</li><li>Answer and End handled through CallKit</li><li>A clear answer for “missed call” and “caller hung up”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ksMFtgZfFOI25QaVnbAXyQ.png" /><figcaption><em>A real VoIP push to my iPhone. iOS draws the whole screen; the app only supplies the name.</em></figcaption></figure><blockquote><em>Code: </em><em>VoIPService.swift in the </em><a href="https://github.com/Sa3doola/NotifyLab"><em>NotifyLab repo</em></a><em>. The call screen needs an iPhone: on the Simulator the push arrives, but CallKit ends the call at once.</em></blockquote><blockquote><em>NotifyLab’s call is a fake: it rings, and you can answer and hang up, but no audio flows. Carrying the voice (WebRTC, SIP) is its own topic.</em></blockquote><h3>How a call reaches a locked phone</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y8q_nPM2mi8SJwqh3Ki1ag.png" /><figcaption><em>Figure 5: the push only wakes the app. The call screen comes from CallKit, and the report to CallKit is not optional.</em></figcaption></figure><p>Two Apple frameworks split the work:</p><ul><li>PushKit receives the push. It has its own token and its own delegate, separate from everything in Parts 3 and 4.</li><li>CallKit shows the call. It draws the same full-screen UI the Phone app uses, on the lock screen, with the ringtone and the slider.</li></ul><p>VoIP pushes differ from alert pushes in almost every way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eTs4-VGk0lk98Ha0J8rnCw.png" /><figcaption><em>VoIP push vs alert push. The last two rows are the ones that bite.</em></figcaption></figure><h3>Step 1: Get the VoIP token</h3><p>You ask PushKit for a VoIP token by creating a PKPushRegistry and saying which push type you want. No permission prompt is involved:</p><pre>/// Registering asks for a VoIP token. No permission prompt is involved.<br>func start() {<br>    registry.delegate = self<br>    registry.desiredPushTypes = [.voIP]<br>}</pre><p>The token arrives in a delegate callback, as Data, just like the APNs token in Part 3:</p><pre>func pushRegistry(_ registry: PKPushRegistry,<br>                  didUpdate pushCredentials: PKPushCredentials,<br>                  for type: PKPushType) {<br>    tokens?.didReceiveVoIPToken(pushCredentials.token)<br>}<br><br>func pushRegistry(_ registry: PKPushRegistry, didInvalidatePushTokenFor type: PKPushType) {<br>    tokens?.didReceiveVoIPToken(nil)<br>}</pre><p>PushTokenStore hex-encodes it and uploads it in the same device record as the others (the voipToken field from Part 3). Treat it exactly like the APNs token: it can change, and when iOS invalidates it, tell your server.</p><p>Two pieces of setup from Part 2 make this work: the Voice over IP background mode (voip in UIBackgroundModes), and the Push Notifications capability. No separate certificate is needed. The .p8 key signs VoIP pushes too.</p><p>I expected the Simulator not to get a VoIP token. On Xcode 27 it does, 80 bytes like its APNs token, and PushKit even delivers real VoIP pushes to it. It’s the call screen that doesn’t work there (Test it, below).</p><h3>Step 2: Report every push to CallKit, first</h3><p>This is the method iOS watches:</p><pre>func pushRegistry(_ registry: PKPushRegistry,<br>                  didReceiveIncomingPushWith payload: PKPushPayload,<br>                  for type: PKPushType,<br>                  completion: @escaping () -&gt; Void) {<br>    let caller = payload.dictionaryPayload[PayloadKey.caller] as? String ?? &quot;Unknown caller&quot;<br>    reportIncomingCall(from: caller)   // FIRST: tell CallKit<br>    completion()                       // THEN: tell PushKit we&#39;re done<br>}</pre><p>And this is the report:</p><pre>/// Shows the system incoming-call screen.<br>func reportIncomingCall(from caller: String) {<br>    let uuid = UUID()<br>    let update = CXCallUpdate()<br>    update.remoteHandle = CXHandle(type: .generic, value: caller)<br>    update.localizedCallerName = caller<br>    update.hasVideo = false<br><br>    calls.insert(CallRecord(id: uuid, caller: caller, date: .now, state: &quot;Ringing&quot;), at: 0)<br>    EventLog.add(&quot;Reported call from \(caller) to CallKit&quot;, source: &quot;voip&quot;)<br><br>    provider.reportNewIncomingCall(with: uuid, update: update) { error in<br>        guard let error else { return }<br>        Task { @MainActor in self.setState(uuid, &quot;Failed: \(error.localizedDescription)&quot;) }<br>    }<br>}</pre><p>Apple’s documentation is blunt about the rule. Since iOS 13, if you receive a VoIP push and don’t report a call to CallKit, the system terminates your app. If you keep doing it, iOS may stop delivering VoIP pushes to your app at all. That’s why VoIP pushes can’t be used for anything but calls anymore: no “silent sync over VoIP”, no “wake up and check mail”.</p><p>So report first, inside this method, before anything slow. Don’t fetch the caller’s photo or open your call server connection before reporting. Report with what the push carries, then update the call once you know more.</p><p>About completion(): Apple&#39;s sample code calls it inside CallKit&#39;s callback, after the report finishes. NotifyLab calls it right after asking CallKit to report, and that rang my iPhone in my tests on iOS 27. Either way, the order is what matters: the report starts before completion().</p><p>The top line of the call screen, <em>“NotifyLab Audio”</em>, is iOS’s own label: your app’s name plus the call type. The provider is configured once:</p><pre>let configuration = CXProviderConfiguration()<br>configuration.supportsVideo = false<br>configuration.maximumCallsPerCallGroup = 1<br>configuration.supportedHandleTypes = [.generic]<br>provider = CXProvider(configuration: configuration)</pre><p>A Swift 6 note: both delegates are declared @preconcurrency, because NotifyLab created the registry with queue: .main and passed queue: nil (the main queue) to the provider. Both frameworks call back on the main thread, so the main-actor conformance is safe.</p><h3>Step 3: Answer and end</h3><p>When the user slides to answer or taps End, CallKit asks your provider delegate to perform the action:</p><pre>func provider(_ provider: CXProvider, perform action: CXAnswerCallAction) {<br>    setState(action.callUUID, &quot;Answered&quot;)<br>    // Start your audio session / WebRTC connection here.<br>    action.fulfill()<br>}<br><br>func provider(_ provider: CXProvider, perform action: CXEndCallAction) {<br>    setState(action.callUUID, &quot;Ended&quot;)<br>    action.fulfill()<br>}</pre><p>Call fulfill() when the action succeeded, or fail() if it didn&#39;t. A real app connects its audio in the answer action, and starts playing sound only when CallKit says the audio session is ready (provider(_:didActivate:)). The Calls tab lists every call with its state, so you can watch these arrive.</p><h3>Step 4: Send it</h3><p>The payload is small. aps stays empty, and the rest is yours (payloads/voip-call.json):</p><pre>{<br>  &quot;aps&quot;: {},<br>  &quot;caller&quot;: &quot;Sara&quot;,<br>  &quot;callId&quot;: &quot;c-7f3a&quot;<br>}</pre><p>The headers are what make it a VoIP push. NotifyLab’s tools set them for the voip type:</p><pre>case &quot;voip&quot;:<br>  return { &quot;apns-push-type&quot;: &quot;voip&quot;, &quot;apns-priority&quot;: &quot;10&quot;, &quot;apns-topic&quot;: `${bundleId}.voip`, &quot;apns-expiration&quot;: &quot;0&quot; };</pre><ul><li>apns-push-type: voip and the topic &lt;bundle ID&gt;.voip. I tried getting each wrong: an alert-type push to a VoIP token, and a VoIP push without the .voip suffix, both came back 400 DeviceTokenNotForTopic.</li><li>apns-expiration: 0: Apple recommends 0 or a few seconds. A call that rings five minutes late is worse than a missed call.</li><li>Priority 10. A call is always urgent.</li></ul><pre>./tools/apns.sh payloads/voip-call.json voip</pre><h3>Missed calls and hang-ups</h3><p>The rule “every VoIP push is a new call” shapes what you send afterwards:</p><ul><li>The caller hangs up while it’s ringing. The app is already awake, because PushKit woke it for the call. Tell it through your own call-signaling connection, and end the call with provider.reportCall(with:endedAt:reason:) and the reason .remoteEnded. If you use a second VoIP push for this instead, the rule still applies: the app must report a call for it, then end it immediately.</li><li>The call was missed. Send a regular alert push: “Missed call from Sara”. To show the caller’s photo, use the communication-notification technique from Part 5 with an INStartCallIntent instead of a message intent, and add INStartCallIntent to NSUserActivityTypes next to INSendMessageIntent.</li><li>Answered on another device. Stop the ringing on this one the same way as a hang-up, through your signaling connection.</li></ul><h3>Test it</h3><p>1. Get the token (iPhone). Run NotifyLab on your iPhone and open Calls. Copy the VoIP token into VOIP_TOKEN in tools/.env.</p><p>2. Ring the phone. Lock the iPhone and send:</p><pre>./tools/apns.sh payloads/voip-call.json voip</pre><p>The full-screen call from <em>Sara</em> appears on the lock screen. Answer it or decline it, then open Calls: the call is listed as <em>Answered</em> or <em>Ended</em>.</p><p>3. Ring it without a push. In Calls, tap Show an incoming call now. It calls the same reportIncomingCall the push handler uses, which is handy when you&#39;re working on the call UI.</p><p>4. Try the Simulator, to see the limit. The Calls tab shows a VoIP token there too. Send the same push to it, and the Status tab’s log shows <em>Reported call from Sara to CallKit</em>: PushKit delivered it, and the app did its part. But CallKit ends the call immediately and no call screen appears. The button in step 3 does the same thing on the Simulator. Use a device for anything you need to see.</p><p>5. The case PushKit is for. Swipe NotifyLab away in the app switcher, lock the phone, and send the push again. The call should still ring: PushKit launches the app in the background just long enough to report it.</p><h3>Production notes</h3><ul><li>VoIP pushes are for calls only. Every one must show a call. Anything else belongs in an alert or silent push (Part 4).</li><li>Report first, fetch later. Call reportNewIncomingCall before any network request. Update the call with a photo or better name afterwards.</li><li>Use your call ID for the CallKit UUID. NotifyLab makes a fresh UUID() for each push. A real app should derive it from the server&#39;s callId, so a duplicate push for the same call doesn&#39;t ring twice, and a hang-up can find the right call.</li><li>Expire calls fast. apns-expiration: 0 (or a few seconds) and priority 10.</li><li>Keep the VoIP token fresh like the APNs token: upload it when it changes, clear it when iOS invalidates it (Part 3).</li><li>Plan for mainland China. Chinese regulators have required CallKit to be switched off for users in mainland China since 2018, and without CallKit you can’t use VoIP pushes at all. The usual fallback there is a regular alert push, often time-sensitive, that opens your own call screen when tapped.</li><li>Send missed calls as alerts, ideally as communication notifications with an INStartCallIntent, so they show the caller&#39;s face.</li><li>Start audio when CallKit says so, in provider(_:didActivate:), not when you think the call starts.</li></ul><p>Next: <a href="https://medium.com/@saadsherif02/ios-notifications-end-to-end-part-7-real-world-delivery-70b996fd32b6">Part 7</a>, Real-world delivery. Why a push that APNs accepted never showed up: Focus, the Scheduled Summary, Low Power Mode, offline phones and interruption levels. Plus every testing tool, from dragging a file onto the Simulator to Apple’s Push Notifications Console and Delivery Log.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdcde506600f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Notifications, End to End — Part 5: Rich and Communication Notifications]]></title>
            <link>https://medium.com/@saadsherif02/ios-notifications-end-to-end-part-5-rich-and-communication-notifications-801799806118?source=rss-272a2ec2e25d------2</link>
            <guid isPermaLink="false">https://medium.com/p/801799806118</guid>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Saad Sherif]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 14:39:54 GMT</pubDate>
            <atom:updated>2026-09-27T14:48:19.227Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A Service Extension that adds a product photo and saves the order before the user opens the app, a message from your driver that shows their photo instead of your app icon, and a Content Extension that draws a live order card on long-press.</em></p><p><em>This is Part 5 of </em><a href="https://medium.com/@saadsherif02/ios-notifications-end-to-end-part-0-which-notification-do-you-need-cf3057ad7b9e"><em>iOS Notifications, End to End</em></a><em>. New to the series? Start with Part 0, the map.</em></p><p>Everything so far has been text. This part adds what makes a notification feel like part of your app: a photo of the parcel, a message that looks like it came from a person, and a card with real UI behind a long-press. None of it needs a new kind of push. It’s the same alert from Part 4, plus two small extensions that iOS runs for you.</p><p>By the end you’ll have:</p><ul><li>A Service Extension that downloads the product photo and saves the order update, before the banner appears</li><li>A fallback that still shows the text when the 30 seconds run out</li><li>A communication notification: the driver’s message with their photo and name, and a Reply button</li><li>A Content Extension with a SwiftUI order card and a <em>Call driver</em> button that works without opening the app</li><li>A way to debug both, and a list of reasons an extension silently doesn’t run</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D2-P2MdoKnLF5c-soZwLbQ.png" /><figcaption><em>The same “shipped” push as Part 4, now with a photo the Service Extension downloaded.</em></figcaption></figure><blockquote><em>Code: the </em><em>NotifyLabService and </em><em>NotifyLabContent folders in the </em><a href="https://github.com/Sa3doola/NotifyLab"><em>NotifyLab repo</em></a><em>. Test on an iPhone: the Simulator runs the Service Extension but can&#39;t draw the thumbnail.</em></blockquote><h3>Two extensions, two moments</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kxyt9zpOKnLYNRvhUahOvA.png" /><figcaption><em>Figure 4: the Service Extension works before the notification is shown; the Content Extension works after the user long-presses it.</em></figcaption></figure><p>Both are separate targets with their own bundle IDs (…notifylab.service and …notifylab.content), and each runs in its own small process. They can&#39;t call into your app. They share data with it through the App Group from Part 2.</p><ul><li>The Service Extension runs <em>before</em> iOS shows a notification. It gets about 30 seconds to change it: add a photo, rewrite the text, decrypt it, save data. It runs only for remote pushes with mutable-content: 1 and a visible title or body, and only if alerts are on for your app. Never for local notifications, never for silent ones.</li><li>The Content Extension runs <em>after</em>, when the user long-presses a notification. It draws your own UI, picked by the notification’s category. It works for local notifications too.</li></ul><h3>The Service Extension</h3><h3>Step 1: Quick work first</h3><p>iOS hands you the notification and a <em>content handler</em>: the function you call, exactly once, with the version to show. NotifyLab does the cheap, important work first, so there’s something good to show even if the slow part fails:</p><pre>guard let content = request.content.mutableCopy() as? UNMutableNotificationContent else {<br>    contentHandler(request.content)<br>    return<br>}<br>// 1. Quick work first. If time runs out later, iOS shows at least this.<br>let update = OrderUpdate(userInfo: content.userInfo)<br>if let update {<br>    SharedOrders.apply(update)   // the app is up to date before the user opens it<br>    if content.title.isEmpty {<br>        content.title = &quot;Order #\(update.orderID): \(update.status.title)&quot;<br>    }<br>    EventLog.add(&quot;Service extension saved order \(update.orderID) → \(update.status.title)&quot;, source: &quot;service&quot;)<br>}<br>let imageURL = update?.imageURL<br>    ?? (content.userInfo[PayloadKey.imageURL] as? String).flatMap(URL.init(string:))<br>lock.withLock {<br>    self.contentHandler = contentHandler<br>    self.bestAttempt = content<br>}</pre><p>SharedOrders.apply(update) writes the new order status into the App Group. When the user taps the banner, the Orders screen is already up to date, with no network request.</p><h3>Step 2: Slow work, download and attach</h3><p>Then the photo. order-shipped.apns carries its URL as a custom key, &quot;image&quot;. The comment in the code says step 3 because step 2, the chat-message branch, has its own section below.</p><pre>// 3. Slow work: download the image and attach it.<br>guard let imageURL else {<br>    finish()<br>    return<br>}<br>Task {<br>    let attachment = await Self.downloadAttachment(from: imageURL)<br>    if attachment != nil {<br>        EventLog.add(&quot;Service extension attached image&quot;, source: &quot;service&quot;)<br>    }<br>    self.finish { content in<br>        if let attachment { content.attachments = [attachment] }<br>        return content<br>    }<br>}</pre><pre>/// Downloads to a temp file with the right extension. iOS uses the file extension to<br>/// work out the type. Limits: image 10 MB, audio 5 MB, video 50 MB.<br>private static func downloadAttachment(from url: URL) async -&gt; UNNotificationAttachment? {<br>    do {<br>        let (downloaded, response) = try await URLSession.shared.download(from: url)<br>        let ext = url.pathExtension.isEmpty<br>            ? ((response.mimeType?.contains(&quot;png&quot;) ?? false) ? &quot;png&quot; : &quot;jpg&quot;)<br>            : url.pathExtension<br>        let file = FileManager.default.temporaryDirectory<br>            .appending(path: &quot;\(UUID().uuidString).\(ext)&quot;)<br>        try FileManager.default.moveItem(at: downloaded, to: file)<br>        return try UNNotificationAttachment(identifier: &quot;image&quot;, url: file)<br>    } catch {<br>        return nil<br>    }<br>}</pre><p>Three rules hide in there:</p><ul><li>The file must be on disk before you create the attachment. A URL to the internet isn’t enough.</li><li>The file extension matters. iOS works out the type from it (unless you pass a type hint), so save downloads as .jpg or .png, never as a bare temp file.</li><li>Stay under the limits: images (JPEG, GIF, PNG) 10 MB, audio 5 MB, video 50 MB. iOS checks the file and moves it into its own store, so don’t try to use it afterwards.</li></ul><h3>Step 3: When time runs out</h3><p>If the download is still going after about 30 seconds, iOS calls serviceExtensionTimeWillExpire(). You must deliver <em>something</em> right away. NotifyLab delivers the &quot;best attempt&quot; from Step 1, the text without the photo:</p><pre>/// iOS is about to kill the extension. Deliver whatever we have.<br>override func serviceExtensionTimeWillExpire() {<br>    EventLog.add(&quot;Service extension ran out of time; showing original text&quot;, source: &quot;service&quot;)<br>    finish()<br>}<br><br>private func finish(_ transform: (UNMutableNotificationContent) -&gt; UNNotificationContent = { $0 }) {<br>    lock.lock()<br>    let handler = contentHandler<br>    let content = bestAttempt<br>    contentHandler = nil<br>    lock.unlock()<br><br>    guard let handler, let content else { return }   // already delivered<br>    handler(transform(content))<br>}</pre><p>The download and the timeout race each other, and the handler must be called exactly once. The lock makes sure whichever path gets there first wins, and the other one finds contentHandler already nil and does nothing. That shared state is also why the class is marked @unchecked Sendable in Swift 6: the lock is what makes it safe, and the compiler can&#39;t see that on its own.</p><p>If you never call the handler, iOS gives up and shows the original notification anyway. You don’t lose the push, but you lose everything you added.</p><h3>Communication notifications: a message with a face</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EBeJX04i7uTpAUg5VEfbzw.png" /><figcaption><em>The driver’s message. The sender’s photo and name replace the app icon; NotifyLab shrinks to a badge.</em></figcaption></figure><p>The same Service Extension can turn an alert into a message from a person. iOS then shows the sender’s photo and name instead of your app icon, treats it like a message from Messages or WhatsApp, and lets it through the Scheduled Summary by default. In NotifyLab it’s the delivery driver writing to you.</p><p>It takes three things:</p><ol><li>The Communication Notifications capability on the app target (Part 2). Automatic signing adds it to your App ID on the next build to a device.</li><li>INSendMessageIntent in the app&#39;s NSUserActivityTypes, shown below.</li><li>Code in the Service Extension that describes the message to the system.</li></ol><p>The second one is three lines in project.yml:</p><pre># Communication notifications (Part 5): the intents the Service Extension donates.<br>NSUserActivityTypes:<br>  - INSendMessageIntent</pre><p>The push itself is an ordinary alert with mutable-content: 1, plus who sent it and which chat it belongs to (payloads/driver-message.apns):</p><pre>{<br>  &quot;Simulator Target Bundle&quot;: &quot;com.yourco.notifylab&quot;,<br>  &quot;aps&quot;: {<br>    &quot;alert&quot;: {<br>      &quot;title&quot;: &quot;Karim, your driver&quot;,<br>      &quot;body&quot;: &quot;I&#39;m outside your building. Which entrance?&quot;<br>    },<br>    &quot;sound&quot;: &quot;default&quot;,<br>    &quot;category&quot;: &quot;MESSAGE&quot;,<br>    &quot;thread-id&quot;: &quot;chat-order-1042&quot;,<br>    &quot;mutable-content&quot;: 1<br>  },<br>  &quot;sender&quot;: {<br>    &quot;id&quot;: &quot;driver-17&quot;,<br>    &quot;name&quot;: &quot;Karim&quot;,<br>    &quot;avatar&quot;: &quot;https://picsum.photos/seed/notifylab-driver/200/200.jpg&quot;<br>  },<br>  &quot;conversationId&quot;: &quot;chat-order-1042&quot;<br>}</pre><p>The alert’s title is a fallback. If the extension fails, the user still sees “Karim, your driver” as a normal notification.</p><p>In the extension, a message takes its own branch:</p><pre>// 2. A message from a person: show it as a communication notification.<br>if let message = ChatMessage(userInfo: content.userInfo, text: content.body) {<br>    Task {<br>        let intent = await Self.donateMessageIntent(for: message)<br>        self.finish { content in<br>            do {<br>                // Swaps the app icon for the sender&#39;s photo and name.<br>                return try content.updating(from: intent)<br>            } catch {<br>                EventLog.add(&quot;updating(from:) failed: \(error.localizedDescription)&quot;, source: &quot;service&quot;)<br>                return content<br>            }<br>        }<br>    }<br>    return<br>}</pre><p>The real work is describing the message in the system’s own words, then <em>donating</em> it:</p><pre>private static func donateMessageIntent(for message: ChatMessage) async -&gt; INSendMessageIntent {<br>    // Pass the photo as bytes. We download it here, inside the extension&#39;s 30 seconds.<br>    var avatar: INImage?<br>    if let url = message.avatarURL, let data = try? await URLSession.shared.data(from: url).0 {<br>        avatar = INImage(imageData: data)<br>    }<br>    let sender = INPerson(<br>        personHandle: INPersonHandle(value: message.senderID, type: .unknown),<br>        nameComponents: nil,<br>        displayName: message.senderName,<br>        image: avatar,<br>        contactIdentifier: nil,<br>        customIdentifier: message.senderID<br>    )<br>    let intent = INSendMessageIntent(<br>        recipients: nil,                          // one-to-one: the user is the recipient<br>        outgoingMessageType: .outgoingMessageText,<br>        content: message.text,<br>        speakableGroupName: nil,<br>        conversationIdentifier: message.conversationID,   // same ID for the whole chat<br>        serviceName: nil,<br>        sender: sender,<br>        attachments: nil<br>    )<br><br>    let interaction = INInteraction(intent: intent, response: nil)<br>    interaction.direction = .incoming<br>    do {<br>        try await interaction.donate()<br>        EventLog.add(&quot;Service extension: message from \(message.senderName) → communication notification&quot;, source: &quot;service&quot;)<br>    } catch {<br>        EventLog.add(&quot;Intent donation failed: \(error.localizedDescription)&quot;, source: &quot;service&quot;)<br>    }<br>    return intent<br>}</pre><p>Piece by piece:</p><ul><li>INPerson is the sender: a stable ID from your backend (driver-17), the display name, and the photo.</li><li>INSendMessageIntent is the message. For a one-to-one chat, recipients is nil: the user is the recipient, and Apple asks you never to list the current user as a participant. conversationIdentifier must be the same for every message in the chat.</li><li>Donating the interaction, marked .incoming, tells the system this conversation happened. Then content.updating(from: intent)returns a new version of the notification with the person&#39;s photo and name.</li><li>Group chats work the same way, with the <em>other</em> participants in recipients, a group name in speakableGroupName, and a group photo set with intent.setImage(groupPhoto, forParameterNamed: \.speakableGroupName).</li></ul><p>About Focus: a communication notification skips the Scheduled Summary by default, but it doesn’t automatically break through a Focus. It gets through when the sender is on that Focus’s list of allowed people, or your app is on its list of allowed apps. The user decides, not you.</p><h3>Reply without opening the app</h3><p>The payload’s category is MESSAGE, which gives the notification a text field:</p><pre>// Chat message from the driver: reply without opening the app.<br>// The sender&#39;s photo comes from the Service Extension (communication notification).<br>let reply = UNTextInputNotificationAction(<br>    identifier: ActionID.messageReply,<br>    title: &quot;Reply&quot;,<br>    options: [],<br>    icon: UNNotificationActionIcon(systemImageName: &quot;arrowshape.turn.up.left&quot;),<br>    textInputButtonTitle: &quot;Send&quot;,<br>    textInputPlaceholder: &quot;Message&quot;<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pyMPlWN13JIUnKiAnuNwvw.png" /><figcaption><em>Long-press, type, Send. The app gets the text in the background and never opens.</em></figcaption></figure><p>The typed text arrives in the same notification router as every other button (Part 1):</p><pre>case ActionID.messageReply:<br>    EventLog.add(&quot;Reply to driver: \(event.typedText ?? &quot;&quot;)&quot;, source: &quot;app&quot;)</pre><p>I tested the whole path on my iPhone: the photo and name replaced the app icon, the Reply text reached the app, and Xcode’s automatic signing added the capability to the App ID and profile by itself on the first ⌘R.</p><h3>The Content Extension: a card behind the long-press</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kDr-BFpU-5izynGAGF3iqA.png" /><figcaption><em>Long-press an order notification and the Content Extension draws this card. The buttons come from the ORDER category.</em></figcaption></figure><p>A Content Extension is a view controller that iOS shows when the user long-presses a notification. Which notifications get it is decided in its Info.plist:</p><pre>NSExtensionAttributes:<br>  UNNotificationExtensionCategory: ORDER          # must match aps.category<br>  UNNotificationExtensionInitialContentSizeRatio: 0.62<br>  UNNotificationExtensionDefaultContentHidden: true   # our card shows title/body itself<br>  UNNotificationExtensionUserInteractionEnabled: false</pre><ul><li>UNNotificationExtensionCategory: only notifications with &quot;category&quot;: &quot;ORDER&quot; get this card. The driver&#39;s message (MESSAGE) doesn&#39;t.</li><li>…InitialContentSizeRatio: height as a fraction of width, used before your view has laid itself out. Get it close to avoid a visible jump.</li><li>…DefaultContentHidden: hides iOS&#39;s own title and body under the card, because the card shows them itself.</li><li>…UserInteractionEnabled: false means taps on the card open the app, and only the action buttons do anything else. Set it to true only if the card has its own controls.</li></ul><p>The view controller hosts a SwiftUI view and fills it from the notification:</p><pre>/// Called with each notification in the group. Update the UI for the newest one.<br>func didReceive(_ notification: UNNotification) {<br>    let content = notification.request.content<br>    card.title = content.title<br>    card.body = content.body<br>    card.update = OrderUpdate(userInfo: content.userInfo)<br>    if let id = card.update?.orderID {<br>        card.timeline = SharedOrders.timelines()[id] ?? []<br>    }<br>    card.image = Self.loadImage(from: content.attachments.first)<br>    card.note = nil<br>    EventLog.add(&quot;Content extension showed the order card&quot;, source: &quot;content&quot;)<br>}</pre><p>The photo the Service Extension attached is available here too, and the timeline comes from the same App Group the Service Extension just wrote to. The two extensions never talk to each other, but they share the same data.</p><h3>Buttons: handle them here, or hand them to the app</h3><p>When the user taps a button under the card, the Content Extension hears about it first and decides:</p><pre>/// Action buttons come here first. We decide: handle in place, or open the app.<br>func didReceive(_ response: UNNotificationResponse,<br>                completionHandler completion: @escaping (UNNotificationContentExtensionResponseOption) -&gt; Void) {<br>    switch response.actionIdentifier {<br>    case ActionID.orderContact:<br>        card.note = &quot;Calling your driver…&quot;<br>        EventLog.add(&quot;Call driver tapped in the content extension&quot;, source: &quot;content&quot;)<br>        completion(.doNotDismiss)              // stay open, card updated<br>    default:<br>        completion(.dismissAndForwardAction)   // e.g. &quot;Track order&quot;: let the app handle it<br>    }<br>}</pre><ul><li>.doNotDismiss: the card stays open and updates. <em>Call driver</em> shows &quot;Calling your driver…&quot; right there.</li><li>.dismissAndForwardAction: the card closes and the action goes to the app&#39;s notification router, as if there were no extension. <em>Track order</em> opens the Orders tab.</li></ul><p>One Swift 6 detail: the class declares @preconcurrency UNNotificationContentExtension. The protocol isn&#39;t marked as main-actor, but a view controller is, and iOS calls these methods on the main thread. @preconcurrency lets the conformance compile, and Swift checks the main thread at runtime.</p><h3>Debugging extensions</h3><p>Extensions fail quietly. The notification just shows up plain, and nothing tells you why. Four habits help:</p><p>Run the extension’s scheme. Pick NotifyLabService (or NotifyLabContent) in Xcode’s scheme menu, press Run, and choose NotifyLabwhen Xcode asks which app to run. Then send a real push. Breakpoints in the extension now stop. You can also attach later: Debug → Attach to Process by PID or Name, type NotifyLabService, and send.</p><p>Don’t test the Service Extension with simctl push. Dragging a file onto the Simulator never runs it. A real sandbox push to the Simulator does run it, but the Simulator can&#39;t draw the thumbnail. Photos need an iPhone.</p><p>Log somewhere you can see. A print in an extension doesn&#39;t show up in your app&#39;s console, because it&#39;s a different process. NotifyLab writes each step to a small log in the App Group, and the Status tab lists it with the process that wrote it: app, service or content. After an order push you see <em>Service extension saved order 1042 → Shipped</em> and <em>Service extension attached image</em>, both from service, a second before the app&#39;s own entry.</p><p>When the Service Extension doesn’t run at all, check in this order:</p><ol><li>The payload has &quot;mutable-content&quot;: 1.</li><li>The alert has a title or body. Sound-only and badge-only pushes don’t count.</li><li>Alerts are on for the app in Settings.</li><li>The extension’s minimum iOS version isn’t newer than the phone’s.</li><li>It didn’t crash. Look for NotifyLabService in the Console app while you send.</li></ol><h3>Test it</h3><p>1. The photo (iPhone). Lock the phone and send:</p><pre>./tools/apns.sh payloads/order-shipped.apns</pre><p>The banner has the parcel photo. The Status tab shows <em>Service extension saved order 1042 → Shipped</em> and <em>attached image</em>.</p><p>2. The card. Long-press the notification. Tap Call driver: the card stays open and says <em>Calling your driver…</em>. Long-press again and tap Track order: the app opens on Orders.</p><p>3. The card without a server. In the app, go to Orders → Preview an update as a local notification. Content Extensions work for local notifications too, so the card appears on long-press, with an image the app drew itself.</p><p>4. The driver’s message.</p><pre>./tools/apns.sh payloads/driver-message.apns</pre><p>Karim’s photo replaces the app icon. Long-press, type a reply, tap Send, and the Status tab shows <em>Reply to driver: …</em>.</p><h3>Production notes</h3><ul><li>Don’t make the Service Extension your data sync. It runs only when alerts are on, only for visible pushes, and only within 30 seconds. Saving data there is a bonus; the app must still sync on launch.</li><li>Always deliver something. Keep a best attempt ready, call the handler exactly once, and make serviceExtensionTimeWillExpire()fast.</li><li>Serve small images over HTTPS. App Transport Security applies to extensions too, and a 200 KB thumbnail arrives long before a 9 MB original.</li><li>Other jobs for the Service Extension: decrypting end-to-end encrypted text (send ciphertext, decrypt on the device), and badge counts kept in the App Group.</li><li>Use communication notifications only for people. A real person writing to the user, like a driver, a friend or a support agent. Not your marketing account.</li><li>Keep conversation IDs stable, and donate outgoing messages too. When the user replies, donate an .outgoing interaction. It helps iOS rank the conversation in Share sheets and Siri suggestions.</li><li>Keep the card light. A Content Extension gets little memory. Show what’s in the notification and the App Group; don’t start large downloads there.</li><li>Test on a device. The Simulator can’t show thumbnails, and simctl push skips the Service Extension entirely.</li></ul><p>Next: <a href="https://medium.com/@saadsherif02/ios-notifications-end-to-end-part-6-voip-calls-fdcde506600f">Part 6</a>, VoIP. Make the phone ring when the app is killed and the screen is locked: PushKit, the separate VoIP token, and the CallKit rule that iOS enforces by ending your app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=801799806118" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Notifications, End to End — Part 4: Sending]]></title>
            <link>https://medium.com/@saadsherif02/ios-notifications-end-to-end-part-4-sending-ded1a52b3532?source=rss-272a2ec2e25d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ded1a52b3532</guid>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Saad Sherif]]></dc:creator>
            <pubDate>Fri, 25 Sep 2026 10:43:40 GMT</pubDate>
            <atom:updated>2026-09-27T14:40:19.986Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The full journey in 15 steps, an APNs request line by line, and three real payloads (an order update, a marketing message and a silent sync), each with the headers that make it behave. Then the same sends through Firebase.</em></p><p><em>This is Part 4 of </em><a href="https://medium.com/@saadsherif02/ios-notifications-end-to-end-part-0-which-notification-do-you-need-cf3057ad7b9e"><em>iOS Notifications, End to End</em></a><em>. New to the series? Start with Part 0, the map.</em></p><p>You have a key (Part 2) and a token (Part 3). Sending is one HTTP request. What makes a push feel right is everything around that request: how urgent it says it is, whether it replaces the last one, how long APNs should keep trying, and what the app does when someone taps it.</p><p>We’re finishing NotifyLab’s Orders and Sync tabs. By the end you’ll have:</p><ul><li>The whole journey from registration to tap, in 15 steps</li><li>Every APNs header explained, and the right value for each kind of push</li><li>An order update that replaces itself instead of piling up, and opens the right screen when tapped</li><li>A marketing push that stays quiet, and the opt-out Apple requires</li><li>A silent push that refreshes data in the background, and the rules that decide whether it arrives</li><li>The same three sends through FCM HTTP v1</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IOPUFhtbjD2tBfPEPr58sg.png" /><figcaption>Code: payloads/, tools/apns.sh and tools/fcm.mjs in the <a href="https://github.com/Sa3doola/NotifyLab">NotifyLab repo</a>. You need the key and tools/.env from Part 2, and a token from Part 3.</figcaption></figure><h3>The journey, start to end</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A9ojUajepGhUak4ISCk30A.png" /><figcaption><em>Figure 2: two loops. Parts 1 to 3 built the first one; this part is the second.</em></figcaption></figure><p>Here’s every step, with the code or API behind it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r1lnlJ-n7HJK1MR_vntPOw.png" /><figcaption><em>The whole journey. This part covers steps 9 to 12, and 15.</em></figcaption></figure><h3>Anatomy of a request</h3><p>Every send to APNs is one HTTP/2 POST. This is the request tools/apns.sh makes, and it&#39;s the same one your server makes in any language:</p><pre>curl --http2 --silent --show-error --include \<br>  -H &quot;authorization: bearer $JWT&quot; \<br>  -H &quot;apns-topic: $TOPIC&quot; \<br>  -H &quot;apns-push-type: $PUSH_TYPE&quot; \<br>  -H &quot;apns-priority: $PRIORITY&quot; \<br>  ${EXTRA[@]+&quot;${EXTRA[@]}&quot;} \<br>  --data &quot;$BODY&quot; \<br>  &quot;https://$HOST/3/device/$TOKEN&quot;</pre><p>(EXTRA adds the optional headers, apns-collapse-id and apns-expiration, when you set them.)</p><p>Four parts:</p><ul><li>The URL: https://api.sandbox.push.apple.com/3/device/&lt;token&gt; for Debug builds, api.push.apple.com for TestFlight and the App Store. HTTP/2 only, on port 443 (or 2197).</li><li>The JWT from Part 2, in authorization.</li><li>The headers, which tell APNs and iOS how to treat this push.</li><li>The body: the JSON payload, at most 4 KB (5 KB for VoIP).</li></ul><p>The headers are where the behavior lives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HD2PaYyyAWcPVYp-SswOIA.png" /><figcaption><em>The six headers, and what each kind of push should send.</em></figcaption></figure><p>APNs answers with a status, an apns-id, and in the sandbox an apns-unique-id you can look up in Apple&#39;s Delivery Log (Part 7):</p><pre>HTTP/2 200<br>apns-id: &lt;a UUID for this request&gt;<br>apns-unique-id: &lt;a UUID you can look up in the Delivery Log&gt;</pre><p>200 means APNs accepted the push. It doesn&#39;t mean the user saw it. Everything after step 12 of the journey happens on the device, and Part 7 is about that.</p><h3>Payload 1: An order update</h3><p>This is payloads/order-out-for-delivery.apns:</p><pre>{<br>  &quot;Simulator Target Bundle&quot;: &quot;com.yourco.notifylab&quot;,<br>  &quot;aps&quot;: {<br>    &quot;alert&quot;: {<br>      &quot;title&quot;: &quot;Your driver is 5 minutes away&quot;,<br>      &quot;body&quot;: &quot;Order #1042 is out for delivery&quot;<br>    },<br>    &quot;sound&quot;: &quot;default&quot;,<br>    &quot;category&quot;: &quot;ORDER&quot;,<br>    &quot;thread-id&quot;: &quot;order-1042&quot;,<br>    &quot;mutable-content&quot;: 1,<br>    &quot;interruption-level&quot;: &quot;time-sensitive&quot;,<br>    &quot;relevance-score&quot;: 1.0<br>  },<br>  &quot;orderId&quot;: &quot;1042&quot;,<br>  &quot;status&quot;: &quot;out_for_delivery&quot;,<br>  &quot;eta&quot;: &quot;5 min&quot;<br>}</pre><p>Everything Apple reads is inside aps:</p><ul><li>alert: the title and body the user sees.</li><li>sound: default, or the name of a sound file in your app.</li><li>category: picks the buttons, the same ORDER category the app registered in Part 1 (<em>Track order</em>, <em>Call driver</em>).</li><li>thread-id: groups this notification with the others for the same order in Notification Center.</li><li>mutable-content: 1: lets the Service Extension change it before it&#39;s shown (Part 5).</li><li>interruption-level and relevance-score: how loud it is (Part 1), and where it sorts in the Scheduled Summary.</li></ul><p>Everything outside aps is yours: orderId, status, eta. iOS passes them to the app untouched, and they&#39;re what the app uses to open the right screen. Send IDs, not content. The app can always fetch the details.</p><p>Simulator Target Bundle is only for the Simulator: it tells it which app the file is for when you drag the file onto it or use xcrun simctl push. NotifyLab&#39;s tools remove it before sending, so it doesn&#39;t count toward the 4 KB.</p><h3>Replace, don’t pile up</h3><p>An order goes through five states. Without a collapse ID, the user ends up with five notifications for one parcel. With one, each update replaces the last:</p><pre>COLLAPSE_ID=order-1042 ./tools/apns.sh payloads/order-out-for-delivery.apns</pre><p>I tested it on the Simulator: I sent <em>“Your driver is 5 minutes away”</em> with apns-collapse-id: order-1042, then <em>&quot;Order #1042 shipped&quot;</em> with the same ID three minutes later. Only the second one was left in Notification Center. The older notifications, sent without a collapse ID, all stayed.</p><p>thread-id and apns-collapse-id sound alike and do different jobs:</p><ul><li>thread-id (in the payload) groups notifications. They all stay, stacked together.</li><li>apns-collapse-id (a header) replaces one. Only the newest stays.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xfm3VptrnSDb4CfNlpK5Lg.png" /><figcaption><em>Two threads from one app: </em><em>order-1042 on top, the habit samples below. Same app, grouped by </em><em>thread-id.</em></figcaption></figure><p>Set an expiration too. “Your driver is 5 minutes away” is useless an hour later. If the phone is off, you don’t want APNs to deliver it tomorrow morning:</p><pre>EXPIRATION=$(( $(date +%s) + 3600 )) COLLAPSE_ID=order-1042 ./tools/apns.sh payloads/order-out-for-delivery.apns</pre><h3>The tap</h3><p>When the user taps, iOS calls the notification delegate from Part 1, and NotifyLab’s router opens the order. NotificationEvent has already copied orderId and status out of userInfo into an OrderUpdate:</p><pre>default:<br>            // Plain tap, or &quot;Track order&quot;: deep-link to the right screen.<br>            if let order = event.order {<br>                orders.apply(order)<br>                navigation.highlightedOrderID = order.orderID<br>                navigation.tab = .orders<br>            } else if event.categoryID == CategoryID.habit {<br>                navigation.tab = .habits<br>            } else if event.categoryID == CategoryID.message {<br>                navigation.tab = .orders<br>            }<br>            EventLog.add(&quot;Opened from notification: \(event.title)&quot;, source: &quot;app&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5NHdT1e7wMBKed-KptU3iw.png" /><figcaption><em>After a tap: the Orders tab, with order #1042 highlighted and its timeline updated from the push.</em></figcaption></figure><p>If the app is already open, willPresent runs instead of a tap. NotifyLab shows the banner and updates the screen in place, so the timeline moves while you watch:</p><pre>/// App is open and a notification arrives. Without this, iOS shows nothing.<br>    func presentInForeground(_ event: NotificationEvent) -&gt; UNNotificationPresentationOptions {<br>        EventLog.add(&quot;Arrived in foreground: \(event.title)&quot;, source: &quot;app&quot;)<br>        if let order = event.order {<br>            orders.apply(order)          // update the screen in place, too<br>        }<br>        return [.banner, .list, .sound, .badge]<br>    }</pre><h3>Payload 2: A marketing message</h3><p>payloads/marketing-passive.apns:</p><pre>{<br>  &quot;Simulator Target Bundle&quot;: &quot;com.yourco.notifylab&quot;,<br>  &quot;aps&quot;: {<br>    &quot;alert&quot;: {<br>      &quot;title&quot;: &quot;New this week&quot;,<br>      &quot;body&quot;: &quot;Five habits people stick with. Tap to read.&quot;<br>    },<br>    &quot;mutable-content&quot;: 1,<br>    &quot;interruption-level&quot;: &quot;passive&quot;,<br>    &quot;relevance-score&quot;: 0.2<br>  },<br>  &quot;image&quot;: &quot;https://picsum.photos/seed/notifylab-promo/600/400.jpg&quot;<br>}</pre><p>What makes it polite:</p><ul><li>No sound, and passive: it goes quietly into Notification Center without lighting up the screen.</li><li>relevance-score: 0.2: it sorts low in the Scheduled Summary.</li><li>Priority 5 in the header: APNs delivers it when it suits the battery, not this second.</li></ul><pre>./tools/apns.sh payloads/marketing-passive.apns marketing</pre><p>Apple’s App Review Guidelines (4.5.4) add a rule of their own: don’t send promotions or marketing by push unless the user explicitly opted in through wording in your app, and give them a way in the app to opt out. The system permission prompt isn’t that consent. Keep a separate “Offers and news” switch, store it on your server, and check it before every marketing send.</p><h3>Payload 3: A silent sync</h3><p>payloads/silent-sync.apns is the smallest payload in the repo:</p><pre>{<br>  &quot;Simulator Target Bundle&quot;: &quot;com.yourco.notifylab&quot;,<br>  &quot;aps&quot;: {<br>    &quot;content-available&quot;: 1<br>  },<br>  &quot;reason&quot;: &quot;new-orders&quot;<br>}</pre><p>content-available: 1 and nothing else in aps: no alert, no sound, no badge. iOS wakes your app in the background, shows nothing, and gives it about 30 seconds. No permission is needed, because nothing is shown. The headers must match: apns-push-type: background and apns-priority: 5. Apple&#39;s docs call priority 10 for a background push an error. When I tried it, the sandbox still answered 200, so nothing will warn you. Follow the docs anyway.</p><pre>./tools/apns.sh payloads/silent-sync.apns background</pre><p>The app side is one app delegate method, plus the Remote notifications background mode from Part 2:</p><pre>/// Runs in the background for ~30 s. Not called if the user force-quit the app.<br>    func application(_ application: UIApplication,<br>                     didReceiveRemoteNotification userInfo: [AnyHashable: Any]) async -&gt; UIBackgroundFetchResult {<br>        await model.sync.handleSilentPush(userInfo)<br>    }</pre><pre>func handleSilentPush(_ userInfo: [AnyHashable: Any]) async -&gt; UIBackgroundFetchResult {<br>        let reason = userInfo[PayloadKey.reason] as? String ?? &quot;unspecified&quot;<br>        EventLog.add(&quot;Silent push woke the app (reason: \(reason))&quot;, source: &quot;app&quot;)</pre><pre>        // Real apps fetch changes from their API here. Finish well within ~30 s,<br>        // or iOS gives your app fewer background wake-ups in the future.<br>        try? await Task.sleep(for: .seconds(1))</pre><pre>        let defaults = AppGroup.defaults<br>        defaults.set(defaults.integer(forKey: &quot;sync.count&quot;) + 1, forKey: &quot;sync.count&quot;)<br>        defaults.set(Date.now, forKey: &quot;sync.date&quot;)<br>        defaults.set(reason, forKey: &quot;sync.reason&quot;)<br>        reload()<br>        return .newData<br>    }</pre><p>A silent push is a hint, not a message. iOS decides whether to deliver it:</p><ul><li>It isn’t guaranteed. Apple says so in as many words, and asks you not to send more than two or three per hour.</li><li>Force-quit kills it. If the user swiped the app away, iOS drops silent pushes until they open it again.</li><li>Low Power Mode and Background App Refresh delay it or stop it. The Sync tab shows both.</li><li>The Simulator won’t wake for it. xcrun simctl push refuses the file (<em>&quot;no user visible content&quot;</em>), and a real sandbox push to the Simulator gets 200 from APNs but never wakes the app. On my iPhone the same push woke the app and the Sync counter went up.</li></ul><p>So never rely on it alone. Sync again every time the app opens, and treat the silent push as a way to be early.</p><h3>The same sends through FCM</h3><p>With Firebase, you send to FCM and FCM calls APNs for you (steps 9–11). NotifyLab’s tools/fcm.mjs reuses the exact same payload files. The whole APNs payload goes into apns.payload, and the APNs headers into apns.headers:</p><pre>// The whole APNs payload goes in apns.payload. FCM passes it through to APNs unchanged,<br>// so custom keys (orderId, status, image) arrive at the top level on the device.<br>const apnsHeaders = headersFor(type, &quot;ignored&quot;);<br>delete apnsHeaders[&quot;apns-topic&quot;]; // FCM sets the topic from the iOS app you registered<br>const message = {<br>  message: {<br>    token: process.env.FCM_TOKEN,<br>    apns: { headers: apnsHeaders, payload: readPayload(file) },<br>  },<br>};</pre><pre>node tools/fcm.mjs payloads/order-out-for-delivery.apns<br>node tools/fcm.mjs payloads/marketing-passive.apns marketing<br>node tools/fcm.mjs payloads/silent-sync.apns background</pre><p>Three things to know:</p><ul><li>Only HTTP v1 exists now. The old “legacy” FCM API with a server key was shut down in 2024. If a tutorial shows Authorization: key=…, it&#39;s out of date.</li><li>You don’t set apns-topic. FCM fills it in from the iOS app registered in your Firebase project.</li><li>The apns block is iOS-only. If the same message also goes to Android, add an android block, or use the shared notificationblock for a plain title and body. NotifyLab sends only to iOS, so it uses the apns block for full control.</li></ul><h3>4 KB, and what to do about it</h3><p>Apple documents the limit as 4 KB (4,096 bytes) for a normal push and 5 KB for VoIP. NotifyLab’s Node sender checks it before sending:</p><pre>const limit = type === &quot;voip&quot; ? 5120 : 4096;<br>  if (Buffer.byteLength(body) &gt; limit) {<br>    return Promise.reject(new Error(`Payload is ${Buffer.byteLength(body)} bytes; the limit is ${limit}.`));<br>  }</pre><p>It counts bytes, not characters. The en dash in “2–4 pm” is one character but three bytes, so order-shipped.apns is 310 characters and 314 bytes.</p><p>I tested where APNs actually draws the line. The sandbox accepted payloads up to 5,120 bytes, and returned 413 PayloadTooLarge at 5,121. Don&#39;t build on that: it&#39;s undocumented, I only checked the sandbox, and Apple can tighten it any day. Stay under 4 KB.</p><p>In practice you never get close if you send IDs, not content. Put orderId in the push and let the app (or the Service Extension) fetch the details.</p><h3>Test it</h3><p>1. An order update. With your token in DEVICE_TOKEN, lock the Simulator or phone and send:</p><pre>COLLAPSE_ID=order-1042 ./tools/apns.sh payloads/order-shipped.apns</pre><p>The <em>“Order #1042 shipped”</em> banner arrives. Leave it there; tapping it would remove it from Notification Center.</p><p>2. Replace it. Send the next update with the same collapse ID:</p><pre>COLLAPSE_ID=order-1042 ./tools/apns.sh payloads/order-out-for-delivery.apns</pre><p>You get a <em>Time Sensitive</em> banner. Pull down Notification Center: only the newest one is left.</p><p>3. Tap it. NotifyLab opens on Orders with the order highlighted.</p><p>4. A quiet one. Send the marketing push:</p><pre>./tools/apns.sh payloads/marketing-passive.apns marketing</pre><p>No banner and no sound. It’s waiting in Notification Center.</p><p>5. A silent sync (iPhone only). Open NotifyLab once, go to the home screen (don’t swipe the app away), and send:</p><pre>./tools/apns.sh payloads/silent-sync.apns background</pre><p>Open the Sync tab: <em>Background wake-ups</em> went up by one, with the reason new-orders.</p><p>6. Through FCM. With FCM_TOKEN set (Part 3), repeat any of the above with node tools/fcm.mjs instead of ./tools/apns.sh.</p><p>Every command also works for many devices at once through the demo server. collapseId is optional:</p><pre>curl -X POST localhost:8080/send -H &#39;content-type: application/json&#39; \<br>  -d &#39;{&quot;file&quot;:&quot;payloads/order-out-for-delivery.apns&quot;,&quot;collapseId&quot;:&quot;order-1042&quot;}&#39;</pre><h3>Production notes</h3><ul><li>200 is not delivered. It means APNs accepted the request. Log the apns-id of every send so you can trace it later (Part 7).</li><li>Match priority to the user’s need. 10 for what they need now, 5 for everything else. Never 10 for a background push.</li><li>Collapse state, expire news. Use apns-collapse-id for anything that has a <em>current</em> state (an order, a score), and apns-expirationfor anything that goes stale (an ETA, a flash sale).</li><li>Marketing needs its own opt-in and an in-app opt-out (App Review Guideline 4.5.4). Check it on the server before every marketing send.</li><li>Silent pushes are hints. Two or three an hour at most, never after a force-quit, never guaranteed. Always sync on launch too.</li><li>Keep connections open. Apple asks providers to reuse HTTP/2 connections across many pushes, and treats rapid connect/disconnect as a denial-of-service pattern. NotifyLab’s tools open one connection per send, which is fine for a demo and wrong for a real server.</li><li>Retry only what can succeed later. Retry 429, 500 and 503 with backoff. Never retry a 400, 403 or 410 unchanged; fix the request or the token instead (Part 2&#39;s error table, Part 3&#39;s cleanup).</li><li>Send IDs, not content. It keeps you far below 4 KB, and the same guideline (4.5.4) says pushes shouldn’t carry sensitive personal or confidential information anyway.</li></ul><p>Next: <a href="https://medium.com/@saadsherif02/ios-notifications-end-to-end-part-5-rich-and-communication-notifications-801799806118">Part 5</a>, Rich and communication notifications. The Service Extension that downloads the product photo and saves the order before the user opens the app, the Content Extension that draws the live order card, and the driver’s message that shows the driver’s photo instead of your app icon.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ded1a52b3532" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Notifications, End to End — Part 3: Device Tokens]]></title>
            <link>https://medium.com/@saadsherif02/ios-notifications-end-to-end-part-3-device-tokens-3c0fabf8807a?source=rss-272a2ec2e25d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c0fabf8807a</guid>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Saad Sherif]]></dc:creator>
            <pubDate>Fri, 25 Sep 2026 09:52:09 GMT</pubDate>
            <atom:updated>2026-09-25T10:44:33.601Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What the APNs token really is, why you get one before the user says yes, when it changes, how Firebase turns it into an FCM token, and the small server table that keeps your push list healthy.</em></p><p><em>This is Part 3 of </em><a href="https://medium.com/@saadsherif02/ios-notifications-end-to-end-part-0-which-notification-do-you-need-cf3057ad7b9e"><em>iOS Notifications, End to End</em></a><em>. New to the series? Start with Part 0, the map.</em></p><p>A device token is an address. Your server can’t push without one, and it can go stale without anyone noticing. The phone never learns that its old token died. Your server finds out on the next send, and only if it’s listening.</p><p>We’re building the token half of NotifyLab’s Orders tab. By the end you’ll have:</p><ul><li>The APNs token on every launch, as a hex string, with no parsing</li><li>FCM wired up with swizzling turned off, so you can see exactly where each token goes</li><li>A device table on your server that the app updates only when something changed</li><li>Dead tokens deleted on the send path, and silent devices pruned after 60 days</li><li>Real sends, through FCM and straight to APNs</li></ul><blockquote><em>Code: </em><em>PushTokenStore.swift, </em><em>FirebaseBridge.swift and </em><em>tools/registry-server.mjs in the </em><a href="https://github.com/Sa3doola/NotifyLab"><em>NotifyLab repo</em></a><em>. You need the key and </em><em>tools/.env from Part 2.</em></blockquote><h3>What a token is, and what it isn’t</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-GsOlUfx5lJNTvCcWR1CsQ.png" /><figcaption><em>The Orders tab on the Simulator. The APNs token here is 80 bytes, so it wraps to four lines. My iPhone’s is 32 bytes.</em></figcaption></figure><ul><li>It’s an address for one app, on one device, in one environment. Change any of the three and you get a different token. A new bundle ID gets a new token. So does a TestFlight build of the same app on the same phone, because it uses production instead of sandbox.</li><li>It has no fixed length. The Simulator gave me 80 bytes (160 hex characters), my iPhone gave me 32 (64 hex). Never parse a token, never check its length, and store it in a text column without a size limit.</li><li>It isn’t permission. You get a token before the user allows anything. Asking and registering are two separate calls.</li><li>It isn’t forever. iOS replaces it at moments your app isn’t told about, which is why you ask for it on every launch.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FhNwuX-Rioi7p7bq5I28aQ.png" /><figcaption><em>Figure 3: the device never knows its token is dead. Your server finds out, on the send path.</em></figcaption></figure><h3>Step 1: Ask for the token on every launch</h3><p>The token request is one line in application(_:didFinishLaunchingWithOptions:), and it runs on every launch:</p><pre>// 3. Ask for the APNs token on EVERY launch. This needs no permission,<br>        //    and it&#39;s how we notice a token that changed since last time.<br>        application.registerForRemoteNotifications()</pre><p>iOS answers through one of two app delegate methods:</p><pre>func application(_ application: UIApplication,<br>                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {<br>        model.tokens.didReceiveAPNsToken(deviceToken)<br>        FirebaseBridge.shared.setAPNsToken(deviceToken)<br>    }</pre><pre>    func application(_ application: UIApplication,<br>                     didFailToRegisterForRemoteNotificationsWithError error: Error) {<br>        // Most common cause: the Push Notifications capability (aps-environment) is missing.<br>        model.tokens.didFailToRegister(error)<br>    }</pre><p>The token arrives as raw bytes (Data). Turn it into hex, and do nothing else with it:</p><pre>func didReceiveAPNsToken(_ token: Data) {<br>        // The token is opaque bytes of no fixed length. Never parse it; just hex-encode it.<br>        let hex = token.map { String(format: &quot;%02x&quot;, $0) }.joined()<br>        if hex != apnsToken { EventLog.add(&quot;APNs token \(hex.prefix(8))… (\(environment.rawValue))&quot;, source: &quot;app&quot;) }<br>        apnsToken = hex<br>        registrationError = nil<br>        Task { await uploadIfNeeded() }<br>    }</pre><p>Two old habits to drop:</p><ul><li>Don’t use deviceToken.description. It prints &quot;32 bytes&quot;, not the token. Old Objective-C code that parsed the description broke in iOS 13.</li><li>Don’t wait for permission before registering. On a fresh install NotifyLab has its token before the user has seen any prompt. The token doesn’t let you <em>show</em> anything; permission decides that. In my tests, a push sent with xcrun simctl push before permission was refused with <em>&quot;Source is not authorized&quot;</em>. But with the app open, willPresent still received it, so the app can react even though iOS draws nothing.</li></ul><h3>When the token changes</h3><p>Apple lists three moments when APNs issues a new token: the user restores a backup onto a device, installs your app on a new device, or reinstalls the operating system. Add the ones you’ll meet while developing: deleting and reinstalling the app, changing the bundle ID, and switching between a Debug build and a TestFlight or App Store build. iOS updates aren’t a documented trigger, but don’t count on the token surviving one either. (If you come from Android: iOS has no “clear app data” that resets it.)</p><p>None of these tell your app anything. Your app only finds out because it asks again on the next launch and compares.</p><h3>Step 2: Upload only when something changed</h3><p>Asking on every launch doesn’t mean uploading on every launch. NotifyLab uploads when any token changed, or when the last upload is more than a week old, so the server’s lastSeenAt stays fresh:</p><pre>/// Upload when a token changed, or at least once a week so the server&#39;s `lastSeenAt` stays fresh.<br>    func uploadIfNeeded(force: Bool = false) async {<br>        guard apnsToken != nil || fcmToken != nil || voipToken != nil else { return }<br>        let fingerprint = [apnsToken, fcmToken, voipToken, environment.rawValue]<br>            .map { $0 ?? &quot;-&quot; }.joined(separator: &quot;|&quot;)<br>        let defaults = UserDefaults.standard<br>        let lastUpload = defaults.object(forKey: &quot;registry.date&quot;) as? Date ?? .distantPast<br>        let isStale = Date.now.timeIntervalSince(lastUpload) &gt; 7 * 24 * 3600<br>        guard force || fingerprint != defaults.string(forKey: &quot;registry.fingerprint&quot;) || isStale else {<br>            uploadStatus = &quot;Server already has these tokens&quot;<br>            return<br>        }<br>        // …<br>        do {<br>            try await DeviceRegistry.upload(makeRecord(), to: base)<br>            defaults.set(fingerprint, forKey: &quot;registry.fingerprint&quot;)<br>            defaults.set(Date.now, forKey: &quot;registry.date&quot;)<br>            // …</pre><p>Apple’s docs say <em>never cache device tokens</em>. The warning is about sending to a saved copy instead of asking iOS. NotifyLab always uses the token iOS just delivered, and keeps the last uploaded value only to compare against.</p><p>What gets uploaded is one record per device, not per user:</p><pre>/// What we send to our backend. One row per device, upserted by `deviceID`.<br>struct DeviceRecord: Codable, Sendable {<br>    let deviceID: String<br>    let userID: String<br>    let platform: String<br>    let bundleID: String<br>    let environment: APSEnvironment<br>    let apnsToken: String?<br>    let fcmToken: String?<br>    let voipToken: String?<br>    let appVersion: String<br>    let osVersion: String<br>}</pre><p>The server adds lastSeenAt every time the device checks in. Here&#39;s my iPhone&#39;s row in the demo server&#39;s database (values shortened):</p><pre>{<br>  &quot;deviceID&quot;: &quot;39C989C6…&quot;,<br>  &quot;userID&quot;: &quot;demo-user&quot;,<br>  &quot;platform&quot;: &quot;ios&quot;,<br>  &quot;bundleID&quot;: &quot;com.yourco.notifylab&quot;,<br>  &quot;environment&quot;: &quot;development&quot;,<br>  &quot;apnsToken&quot;: &quot;75efc2bd…&quot;,<br>  &quot;fcmToken&quot;: &quot;f2Jh4KjD…&quot;,<br>  &quot;voipToken&quot;: &quot;56f1c779…&quot;,<br>  &quot;appVersion&quot;: &quot;1.0&quot;,<br>  &quot;osVersion&quot;: &quot;27.0&quot;,<br>  &quot;lastSeenAt&quot;: &quot;2026-09-24T03:18:10.449Z&quot;<br>}</pre><p>environment matters as much as the token. It tells the server which APNs host to use (Part 2). voipToken is a third, separate token for calls, from PushKit; Part 6 covers it.</p><h3>Step 3: Add FCM</h3><p>Firebase Cloud Messaging sits between your server and APNs. You send to FCM, and FCM calls APNs with the .p8 key you uploaded. You get one API for iOS and Android, topics, and a console. The price is one more hop and one more token to keep fresh.</p><p>The FCM token isn’t a replacement for the APNs token. It’s built from it: the Firebase SDK takes your APNs token, registers it with FCM, and hands you an FCM token that points to it. In NotifyLab’s log both arrive in the same second at launch.</p><p>1. Register the app in Firebase. In the Firebase console, add an iOS app with your bundle ID and download GoogleService-Info.plist.</p><p>2. Upload your APNs key. Project settings → Cloud Messaging → Apple app configuration. Firebase has two slots, development and production. A key that covers both environments (like the one from Part 2) goes in both:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*k7B-5jeYr_XNdGdvBWtefg.png" /><figcaption><em>One </em><em>.p8 in both slots. Firebase needs the Key ID and Team ID too, the same two from Part 2.</em></figcaption></figure><p>3. Add the SDK. Only the FirebaseMessaging product is needed. In NotifyLab it’s in project.yml:</p><pre># FCM (Part 3). Only the FirebaseMessaging product is linked.<br>packages:<br>  Firebase:<br>    url: https://github.com/firebase/firebase-ios-sdk<br>    from: 12.19.0</pre><p>The plist stays in the git-ignored secrets/ folder, so every reader brings their own. A small build step copies it into the app, but only if it&#39;s there:</p><pre># FCM (Part 3): GoogleService-Info.plist lives in the git-ignored secrets/ folder, and each<br>    # developer brings their own. It&#39;s copied in only if it&#39;s there, so a fresh clone still builds<br>    # (with FCM off). A normal file reference would fail with &quot;Build input file cannot be found&quot;.<br>    postBuildScripts:<br>      - name: Copy GoogleService-Info.plist if present<br>        basedOnDependencyAnalysis: false<br>        script: |<br>          PLIST=&quot;$SRCROOT/secrets/GoogleService-Info.plist&quot;<br>          if [ -f &quot;$PLIST&quot; ]; then<br>            cp &quot;$PLIST&quot; &quot;$TARGET_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH/&quot;<br>          fi</pre><p>Why not add the file to the project like any other? Because anyone who clones your repo doesn’t have your plist, and Xcode stops with <em>“Build input file cannot be found”</em>. With the script, a fresh clone builds and runs with FCM off, and once you drop your plist into secrets/, the next build picks it up.</p><p>4. Decide on swizzling. By default the Firebase SDK <em>swizzles</em> your app delegate: it quietly intercepts the APNs token callback and hands the token to FCM itself. It works, but you can’t see it happen, and it can clash with other SDKs that do the same. NotifyLab turns it off in Info.plist:</p><pre># We hand the APNs token to Firebase ourselves (see FirebaseBridge.swift)<br>        FirebaseAppDelegateProxyEnabled: false</pre><p>With swizzling off, passing the token is your job. It’s the second line of the didRegister… callback in Step 1, and it lands here:</p><pre>func configure(tokens: PushTokenStore) {<br>        // FirebaseApp.configure() crashes without the plist, so check first.<br>        guard Bundle.main.path(forResource: &quot;GoogleService-Info&quot;, ofType: &quot;plist&quot;) != nil else {<br>            EventLog.add(&quot;Firebase added, but GoogleService-Info.plist is missing&quot;, source: &quot;app&quot;)<br>            return<br>        }<br>        self.tokens = tokens<br>        FirebaseApp.configure()<br>        Messaging.messaging().delegate = self<br>    }</pre><pre>    /// Info.plist sets FirebaseAppDelegateProxyEnabled = NO (no swizzling),<br>    /// so we hand the APNs token to FCM ourselves. FCM maps it to an FCM token.<br>    func setAPNsToken(_ token: Data) {<br>        guard isAvailable else { return }<br>        Messaging.messaging().apnsToken = token<br>    }</pre><p>Forget that line and FCM never gives you a token, because it has no APNs token to point it at. The FCM row in the Orders tab never fills in, and the Xcode console says <em>“Declining request for FCM Token since no APNS Token specified”</em>. If you ask for the token yourself, you get error 505, <em>“No APNS token specified before fetching FCM Token”</em>. Before FirebaseMessaging 10.4 the SDK handed out a token anyway, so older answers online describe a token that looks fine and delivers nothing.</p><p>5. Listen for the FCM token. Firebase calls this on every launch and whenever the token changes. Treat it exactly like the APNs callback: store it and upload if it changed.</p><pre>extension FirebaseBridge: MessagingDelegate {<br>    /// Called on launch and whenever the FCM token changes (reinstall, restore, new APNs token…).<br>    nonisolated func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {<br>        Task { @MainActor in<br>            self.tokens?.didReceiveFCMToken(fcmToken)<br>        }<br>    }<br>}</pre><h3>Step 4: Clean up on the send path</h3><p>A token dies silently. The only reliable signal is the answer to your next send, so cleanup belongs where you send. NotifyLab’s demo server (tools/registry-server.mjs) does three things around every send:</p><pre>const db = load();<br>  pruneStale(db);<br>  // …<br>  for (const device of Object.values(db)) {<br>    // …<br>    const action = verdict(result);<br>    // 410: dead token. Delete it, unless the device uploaded it again after APNs gave up on it.<br>    const uploadedSince = result.timestamp &amp;&amp; Date.parse(device.lastSeenAt) &gt; result.timestamp;<br>    if (action === &quot;delete&quot; &amp;&amp; !uploadedSince) delete db[device.deviceID];</pre><ol><li>Delete on 410. APNs answers 410 (<em>Unregistered</em> or <em>ExpiredToken</em>) for a token it will never deliver to again, with a timestamp saying when it gave up. If the device uploaded the same token <em>after</em> that moment, it&#39;s alive again, so keep it.</li><li>Prune the silent ones. A device that hasn’t checked in for 60 days gets removed:</li></ol><pre>// The app re-uploads at least weekly. Firebase suggests treating a month of silence as stale;<br>// we give a device two months to come back before we stop sending to it.<br>const STALE_DAYS = 60;</pre><pre>function pruneStale(db) {<br>  const cutoff = Date.now() - STALE_DAYS * 24 * 3600 * 1000;<br>  for (const [id, device] of Object.entries(db)) {<br>    if (Date.parse(device.lastSeenAt) &lt; cutoff) delete db[id];<br>  }<br>}</pre><ol><li>Don’t delete on everything else. 400 BadDeviceToken usually means the wrong environment, not a dead token (Part 2). Deleting there throws away good tokens.</li></ol><p>“Token expiry” confuses people because it means four different things:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kA9QdYb0SGpUj4s0dQgFOg.png" /><figcaption><em>Four things people mean by “the token expired”. Only one of them is a real timer on iOS.</em></figcaption></figure><h3>Test it</h3><p>1. See both tokens. Run NotifyLab on the Simulator and open Orders. The APNs token is 160 hex characters, the FCM token a longer string with a colon in it, and the environment says development · api.sandbox.push.apple.com. The Status tab&#39;s event log shows the order they arrived in:</p><pre>[app] APNs token 80a7e14f… (development)<br>[app] FCM token d3nxo9Ak…</pre><p>Run it on an iPhone and the APNs token is 64 characters.</p><p>2. Get a token without permission. Delete NotifyLab from the Simulator, run it again, and open Orders before you touch <em>Turn on reminders</em>. The token is already there.</p><p>3. Upload it. Start the demo server:</p><pre>node tools/registry-server.mjs</pre><p>In the app, go to Orders → Your server, enter http://localhost:8080 (on an iPhone, use your Mac&#39;s IP), and tap Upload tokens now. The server prints one line per upload, and you can list what it stored:</p><pre>curl localhost:8080/devices</pre><p>4. Send through FCM. Copy the FCM token into FCM_TOKEN in tools/.env, set FCM_SERVICE_ACCOUNT to your Firebase service-account JSON (Project settings → Service accounts → Generate new private key), then:</p><pre>node tools/fcm.mjs payloads/order-shipped.apns</pre><pre>200 {<br>  &quot;name&quot;: &quot;projects/&lt;your-project-id&gt;/messages/&lt;id&gt;&quot;<br>}</pre><p>When I ran this against the Simulator, the order banner arrived a second later, and the event log showed the Service Extension saving the order: FCM → APNs → device, the whole way.</p><p>5. See what a bad token looks like. Values from the shell win over tools/.env, so you can try one without editing the file:</p><pre>FCM_TOKEN=not-a-real-token node tools/fcm.mjs payloads/order-shipped.apns</pre><pre>400 {<br>  &quot;error&quot;: {<br>    &quot;code&quot;: 400,<br>    &quot;message&quot;: &quot;The registration token is not a valid FCM registration token&quot;,<br>    &quot;status&quot;: &quot;INVALID_ARGUMENT&quot;,<br>    …</pre><p>A token that was valid and then died gets 404 UNREGISTERED instead, which is your signal to delete it. Be careful with INVALID_ARGUMENT: FCM also uses it for a broken payload, so check the payload before you delete the token.</p><h3>Production notes</h3><ul><li>One row per device, not per user. A user has several devices, and a shared device can change users. Upsert by device ID and send to every device of the user.</li><li>On logout, detach the device on your server. Clear its userID so the next person on that phone doesn&#39;t get the last person&#39;s pushes. Don&#39;t call unregisterForRemoteNotifications(); Apple reserves it for rare cases, like a new app version that drops push entirely.</li><li>Store the environment with every token, and pick the APNs host from it (Part 2).</li><li>Store tokens as text of any length. A CHAR(64) column will break on the first token that isn&#39;t 32 bytes.</li><li>Upload on change, plus a weekly check-in. Prune after a fixed silence (a month to two), and delete on 410 and FCM&#39;s 404 on the send path.</li><li>Pick one path per device. If you store both tokens, send through FCM <em>or</em> straight to APNs, never both, or the user gets every notification twice.</li><li>identifierForVendor resets too. It changes when the user deletes all your apps, just like the token. A new device ID is a new row; the old one gets pruned.</li><li>Treat tokens as personal data. Delete a user’s device rows when they delete their account.</li></ul><p>Next: <a href="https://medium.com/@saadsherif02/ios-notifications-end-to-end-part-4-sending-ded1a52b3532">Part 4</a>, Sending. The full journey in 15 steps, an APNs request line by line, and three real payloads (an order update, a marketing message and a silent sync), each with the headers that make it behave, plus the same sends through FCM’s apns block.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c0fabf8807a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Notifications, End to End — Part 2: Wiring Up Push]]></title>
            <link>https://medium.com/@saadsherif02/ios-notifications-end-to-end-part-2-wiring-up-push-b1787b828cdb?source=rss-272a2ec2e25d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1787b828cdb</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[push-notification]]></category>
            <dc:creator><![CDATA[Saad Sherif]]></dc:creator>
            <pubDate>Fri, 25 Sep 2026 09:43:52 GMT</pubDate>
            <atom:updated>2026-09-25T09:53:07.873Z</atom:updated>
            <content:encoded><![CDATA[<p><em>App ID, capabilities, entitlements and the </em><em>.p8 key: every switch you flip once, what each one really changes, and how to prove it worked before you write any push code.</em></p><p><em>This is Part 2 of </em><a href="https://medium.com/@saadsherif02/ios-notifications-end-to-end-part-0-which-notification-do-you-need-cf3057ad7b9e"><em>iOS Notifications, End to End</em></a><em>. New to the series? Start with Part 0, the map.</em></p><p>Local notifications needed nothing from Apple. Remote ones need four things to line up: an App ID with push turned on, a build signed with the right entitlement, a key your server signs its requests with, and the same environment on both sides. When one of them is off, nothing crashes. The push just never arrives, and APNs gives you a one-word reason, if you’re lucky enough to be looking.</p><p>By the end of this part you’ll have:</p><ul><li>Push turned on for your App ID, plus the capabilities NotifyLab needs for alerts, silent pushes, calls, time-sensitive and communication notifications</li><li>A signed build you can prove carries aps-environment</li><li>A .p8 key, stored as a secret, and the JWT your server signs with it</li><li>A one-command check that your key works, before you have a device</li><li>Your first real push, answered with 200</li></ul><blockquote><em>You need a paid Apple Developer Program membership ($99 a year). The free Personal Team can’t use push notifications.</em></blockquote><blockquote><em>Code: </em><em>project.yml, </em><em>tools/lib/apns.mjs and </em><em>tools/check-key.mjs in the </em><a href="https://github.com/Sa3doola/NotifyLab"><em>NotifyLab repo</em></a><em>.</em></blockquote><h3>Two chains that meet at APNs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YM0KgNqUSSAdnsx9aQlnxw.png" /><figcaption><em>Figure 1: the app side and the server side never touch, except at APNs.</em></figcaption></figure><p>Setup is two separate chains.</p><p>The app chain runs through the first two columns. Your bundle ID gets an App ID on Apple’s developer portal. Turning on push for that App ID changes the provisioning profile. The profile allows the aps-environment entitlement, and Xcode signs it into the build. That one value decides which APNs server your device tokens work with.</p><p>The key chain is the red line. You create a .p8 key on the same portal, but it never goes into the app. It goes to your server, or to Firebase, which uses it to sign every request to APNs.</p><p>The two chains share only two things: your bundle ID (the server sends it as apns-topic) and the environment (sandbox or production). Most setup bugs are one of those two not matching.</p><h3>Step 1: The App ID</h3><p>A bundle ID is the name in your Xcode project, like com.yourco.notifylab. An App ID is Apple&#39;s record of that name on developer.apple.com, with the list of capabilities your app is allowed to use. Push needs an explicit App ID. A wildcard like com.yourco.*can&#39;t have push.</p><p>With automatic signing you rarely create the App ID yourself. Xcode registers it the first time you build for a device, and ticks Push Notifications when you add the capability in Step 2. It’s still worth opening once to see what Xcode did: Certificates, Identifiers &amp; Profiles → Identifiers → your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qQQ-gtSohMuqlOL0ThjNkg.png" /><figcaption><em>The App ID after Xcode’s automatic signing. Leave Broadcast Capability off; it’s for Live Activities.</em></figcaption></figure><p>NotifyLab keeps every ID in one place in project.yml:</p><pre>    # The ONE place the IDs come from. Bundle IDs and the App Group are derived from it:<br>    #   app          $(BUNDLE_ID_PREFIX).notifylab<br>    #   extensions   $(BUNDLE_ID_PREFIX).notifylab.service / .content<br>    #   App Group    group.$(BUNDLE_ID_PREFIX).notifylab<br>    BUNDLE_ID_PREFIX: com.yourco<br>    APP_GROUP_ID: group.$(BUNDLE_ID_PREFIX).notifylab</pre><p>To make them yours, run one command. It rewrites project.yml, the payload files and the tool configs, then regenerates the Xcode project:</p><pre>./tools/set-bundle-prefix.sh com.yourname</pre><p>Then set DEVELOPMENT_TEAM in project.yml to your Team ID (Step 4 shows where to find it) and run xcodegen generate. Picking your team in Xcode also works, until the next xcodegen generate resets it.</p><h3>Step 2: Capabilities, and what each switch changes</h3><p>In Xcode, select the NotifyLab target → Signing &amp; Capabilities → + Capability. NotifyLab uses five for notifications, plus Local Network, which only lets the demo reach the token server on your Mac:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qm4t6AmnVekT5RqfhYTrsw.png" /><figcaption><em>The NotifyLab target. With “Automatically manage signing” on, Xcode updates the App ID and the profile for you.</em></figcaption></figure><p>Each one writes something different, to a different place:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-UKU2u75l3tT6yg070Xr7g.png" /><figcaption><em>What each capability writes, and where.</em></figcaption></figure><p>Two things in that table save hours:</p><ol><li>Background Modes are not entitlements. They’re a list in Info.plist (UIBackgroundModes). They don&#39;t touch your App ID or your profile. The other capabilities are entitlements: your provisioning profile has to allow them, which is why Xcode updates the App ID when you add one.</li><li>The extensions need App Groups, and nothing else. A Notification Service Extension never gets a device token, so it doesn’t need Push Notifications. It does share data with the app, so it needs the same App Group.</li></ol><p>When I added Communication Notifications for Part 5, I never opened the portal. The next ⌘R to my iPhone added the capability to the App ID and made a new profile, all through automatic signing. With manual signing you’d get an error like <em>“Provisioning profile … doesn’t include the com.apple.developer.usernotifications.communication entitlement”</em> until you tick it on the App ID yourself.</p><p>NotifyLab generates its Xcode project with XcodeGen, so its capabilities are text in project.yml rather than clicks. For the app target:</p><pre>    info:<br>      path: NotifyLab/Info.plist<br>      properties:<br>        # …<br>        # Background Modes capability: silent pushes + VoIP pushes<br>        UIBackgroundModes:<br>          - remote-notification<br>          - voip<br>        # …<br>        # Communication notifications (Part 5): the intents the Service Extension donates.<br>        NSUserActivityTypes:<br>          - INSendMessageIntent<br>    entitlements:<br>      path: NotifyLab/NotifyLab.entitlements<br>      properties:<br>        aps-environment: development<br>        com.apple.developer.usernotifications.time-sensitive: true<br>        com.apple.developer.usernotifications.communication: true<br>        com.apple.security.application-groups:<br>          - $(APP_GROUP_ID)</pre><p>And each extension gets only the App Group:</p><pre>    entitlements:<br>      path: NotifyLabService/NotifyLabService.entitlements<br>      properties:<br>        com.apple.security.application-groups:<br>          - $(APP_GROUP_ID)</pre><p>If you click through Xcode instead, you end up with the same .entitlements file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*7uTtu5wU3XQ6rwjjnJ-G2A.png" /></figure><h3>Step 3: aps-environment, the value that picks the server</h3><p>APNs runs two separate environments:</p><ul><li>Sandbox, api.sandbox.push.apple.com: for apps you run from Xcode</li><li>Production, api.push.apple.com: for TestFlight and the App Store</li></ul><p>A device token belongs to exactly one of them, and the build’s aps-environment entitlement decides which. You don&#39;t switch it by hand. Xcode sets it from the provisioning profile: a development profile gives development, and TestFlight and App Store builds get production when you export them.</p><p>Send a development token to the production server and APNs answers 400 BadDeviceToken. The token is fine; the server is wrong. It&#39;s the classic &quot;worked yesterday&quot; bug: the first TestFlight build goes out, and the server still talks to sandbox.</p><p>Don’t trust the file, check the build. The entitlements file is only a request. What counts is what got signed:</p><pre>codesign -d --entitlements - --xml NotifyLab.app | plutil -p -</pre><p>On my iPhone build (Team ID and bundle ID prefix replaced):</p><pre>{<br>  &quot;application-identifier&quot; =&gt; &quot;ABCDE12345.com.yourco.notifylab&quot;<br>  &quot;aps-environment&quot; =&gt; &quot;development&quot;<br>  &quot;com.apple.developer.team-identifier&quot; =&gt; &quot;ABCDE12345&quot;<br>  &quot;com.apple.developer.usernotifications.communication&quot; =&gt; true<br>  &quot;com.apple.developer.usernotifications.time-sensitive&quot; =&gt; true<br>  &quot;com.apple.security.application-groups&quot; =&gt; [<br>    0 =&gt; &quot;group.com.yourco.notifylab&quot;<br>  ]<br>  &quot;get-task-allow&quot; =&gt; true<br>}</pre><p>Read two things. aps-environment is development, so this build&#39;s token works with sandbox only. And $(APP_GROUP_ID) has become a real group name. For a release, run the same command on the .app inside your exported .ipa. It must say production.</p><p>Run it on a device build. Simulator builds don’t carry signed entitlements, so for them the command prints an empty {}.</p><h3>Step 4: The key (.p8)</h3><p>Go to Certificates, Identifiers &amp; Profiles → Keys → +:</p><ol><li>Give it a name, like <em>NotifyLab APNs</em>.</li><li>Tick Apple Push Notifications service (APNs), then click Configure.</li><li>Choose the environment (sandbox, production, or both) and the key restriction (team-scoped, or topic-specific with the bundle IDs it may push to). The next section helps you choose.</li><li>Continue → Register → Download.</li></ol><p>You can download the .p8 once. Put it somewhere safe right away. If you lose it, the only fix is a new key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7CYRA3k1wZMXEBsydDDr6A.png" /><figcaption><em>The key’s page after registering. Your server sends the Key ID (hidden here) in every JWT.</em></figcaption></figure><p>Note two IDs next to the file. Both are 10 characters:</p><ul><li>Key ID: on the key’s page.</li><li>Team ID: under Membership details in your account.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*qVV9FuAwFWPJJ6ZOGK7nxg.png" /></figure><h3>Key scoping (new in February 2025)</h3><p>Until 2025, every APNs key could push to every app in your team, in both environments. A development key on a laptop could push to your real users. On February 17, 2025 Apple added two restrictions you set when you create a key:</p><ul><li>Environment. A key can be limited to sandbox or to production. Apple now recommends one key per environment. Keys that cover both still work.</li><li>Scope. A team-scoped key covers every app in your team, and you can have at most 2 per environment. A topic-specific key covers only the bundle IDs you pick, up to 200 keys per environment. That suits large companies with many apps and teams.</li></ul><p>Keys made before the change keep working for everything, so nothing forces you to rotate.</p><p>For this tutorial I made one team-scoped key for both environments, because it’s the simplest to learn with. For a real app, make separate sandbox and production keys, so a key that lives on developer machines can’t reach production.</p><h3>.p8 or .p12?</h3><p>Older tutorials export a push certificate (.p12) from Keychain. It still works, but in 2026 there&#39;s little reason to start there:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O2VZrJSaQL6uro03MdYZxQ.png" /><figcaption><em>Auth key vs certificate. The yearly expiry is the real cost.</em></figcaption></figure><p>A certificate expires on a date nobody remembers, and push stops that morning. A key never expires. You rotate it when <em>you</em> choose.</p><h3>Where the key goes, and where it doesn’t</h3><ul><li>Never in the app. The app doesn’t need it, and anything inside an app bundle can be extracted.</li><li>Never in git. NotifyLab keeps it in secrets/, which is git-ignored, and points to it from tools/.env, which is git-ignored too.</li><li>On your server: in a secret manager, not in a config file in the repo.</li><li>In Firebase: Project settings → Cloud Messaging → Apple app configuration → upload. Firebase then signs the APNs requests for you (Part 3).</li></ul><h3>Step 5: What your server does with the key (the JWT)</h3><p>Your server never sends the key to APNs. It uses the key to sign a short token, a JWT, and sends that in the authorization header of every request. The JWT says which key signed it (kid, the Key ID), which team it belongs to (iss, the Team ID), and when it was made (iat).</p><p>NotifyLab’s tools do it in a few lines of Node, with no dependencies (tools/lib/apns.mjs):</p><pre>// APNs rejects a JWT older than 60 min, and one refreshed more often than every 20 min.<br>// Cache it for 50 min.<br>let cached = { token: null, issuedAt: 0 };<br><br>/** Provider token: header {alg: ES256, kid: Key ID}, claims {iss: Team ID, iat: now}. */<br>export function makeJWT({ teamId, keyId, keyPath }) {<br>  const now = Math.floor(Date.now() / 1000);<br>  if (cached.token &amp;&amp; now - cached.issuedAt &lt; 50 * 60) return cached.token;<br><br>  const header = base64url(https://medium.com/JSON.stringify(%7B%20alg:%20&quot;ES256&quot;,%20kid:%20keyId%20%7D));<br>  const claims = base64url(https://medium.com/JSON.stringify(%7B%20iss:%20teamId,%20iat:%20now%20%7D));<br>  const key = createPrivateKey(readFileSync(resolve(root, keyPath)));<br>  // JWT wants the raw r||s signature (IEEE P1363), not DER. This is the classic bug.<br>  const signature = sign(&quot;sha256&quot;, Buffer.from(`${header}.${claims}`), { key, dsaEncoding: &quot;ieee-p1363&quot; });<br><br>  cached = { token: `${header}.${claims}.${base64url(https://medium.com/signature)}`, issuedAt: now };<br>  return cached.token;<br>}</pre><p>Three rules come with it:</p><ul><li>ES256 only. The .p8 is an elliptic-curve key, and APNs accepts no other algorithm.</li><li>Reuse each JWT for 20 to 60 minutes. Older than an hour gets 403 ExpiredProviderToken. A new one more often than every 20 minutes gets 429 TooManyProviderTokenUpdates. Signing a fresh JWT for every request is how you hit the second one.</li><li>Mind the signature format. Node’s default ECDSA signature is DER-encoded, but a JWT needs the raw 64-byte r||s. Get it wrong and every request fails with 403 InvalidProviderToken, even though your key is fine.</li></ul><p>With Firebase you skip all of this. It signs with the .p8 you uploaded.</p><h3>Test it</h3><ol><li>Fill in tools/.env.</li></ol><pre>cp tools/.env.example tools/.env</pre><p>Set TEAM_ID, KEY_ID, KEY_PATH (for example secrets/AuthKey_XYZ9876543.p8) and BUNDLE_ID.</p><p>2. Check the key. No device needed.</p><pre>node tools/check-key.mjs</pre><p>It sends a push to a made-up device token (64 zeros). APNs checks your JWT before the token, so the answer tells you whether your key works:</p><pre>sandbox     400 BadDeviceToken  ✓ key accepted<br>production  400 BadDeviceToken  ✓ key accepted</pre><p>Here BadDeviceToken is the good answer: APNs accepted your key, then rejected the fake token. With a typo in the Key ID you&#39;d see this instead:</p><pre>sandbox     403 InvalidProviderToken  ✗ check KEY_ID, TEAM_ID and KEY_PATH<br>production  403 InvalidProviderToken  ✗ check KEY_ID, TEAM_ID and KEY_PATH</pre><p>One limit: it can’t check BUNDLE_ID, because APNs rejects the fake token before it looks at the topic.</p><p>3. Check the signed build. Run NotifyLab on your iPhone once (⌘R). In Xcode choose Product → Show Build Folder in Finder, open Products/Debug-iphoneos, and run the codesign command from Step 3 on NotifyLab.app. Look for &quot;aps-environment&quot; =&gt; &quot;development&quot;.</p><p>4. Send your first push. Part 3 is all about device tokens. For now, just copy yours: open NotifyLab on the iPhone → Orders → APNs device token, paste it into DEVICE_TOKEN in tools/.env, then:</p><pre>./tools/apns.sh payloads/order-shipped.apns</pre><pre>→ api.sandbox.push.apple.com  type=alert  priority=10  topic=com.yourco.notifylab  bytes=314<br>HTTP/2 200<br>apns-id: &lt;a UUID for this request&gt;<br>apns-unique-id: &lt;a UUID you can look up in the Delivery Log&gt;</pre><p>200 means APNs accepted it, and the banner should appear on the phone. The first time I ran this for the article, APNs answered 400 MissingDeviceToken, because I&#39;d left DEVICE_TOKEN empty. APNs error names are that literal, so read them before you debug anything else:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bklWhpK30yjTMNZV-KmNjA.png" /><figcaption><em>The first responses you’ll meet, and what to do about each.</em></figcaption></figure><h3>Production notes</h3><ul><li>Keep the .p8 in a secret manager. With the key, its Key ID and your Team ID, anyone can push to your users. For a team-scoped key, that&#39;s every app in your team.</li><li>One key per environment. Since February 2025 you can restrict keys, so do it for anything real. Use topic-specific keys when many apps or teams share one account.</li><li>Rotate without downtime. Create the new key, deploy it, then revoke the old one. Requests signed with a revoked key fail right away with 403 InvalidProviderToken. Two team-scoped keys per environment is exactly enough for that overlap.</li><li>Store the environment next to every token. Debug and TestFlight builds of the same app produce tokens for different servers. NotifyLab’s app uploads environment with its token, and the registry server picks the APNs host from it.</li><li>Update your server’s trust store. APNs switched to server certificates from the <em>USERTrust RSA Certification Authority</em> on January 20, 2025 (sandbox) and February 24, 2025 (production). An old trust store fails with a TLS error before any HTTP response. Current OS and Node certificate bundles already include it; a CA file pinned in your repo may not.</li><li>HTTP/2 only. APNs refuses HTTP/1.1. Use port 443, or 2197 if your network blocks 443.</li><li>Check every release build. Run codesign on the app inside the exported .ipa. aps-environment must say production.</li></ul><p>Next: <a href="https://medium.com/@saadsherif02/ios-notifications-end-to-end-part-3-device-tokens-3c0fabf8807a">Part 3</a>, Device tokens. What the token really is, why it isn’t a fixed length (80 bytes on the Simulator, 32 on my iPhone), why you get one before the user says yes, when it changes, and how Firebase swaps it for an FCM token.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1787b828cdb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Notifications, End to End — Part 1: Ask Well, Remind Well]]></title>
            <link>https://medium.com/@saadsherif02/ios-notifications-end-to-end-part-1-ask-well-remind-well-c8800c253ae2?source=rss-272a2ec2e25d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8800c253ae2</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Saad Sherif]]></dc:creator>
            <pubDate>Fri, 25 Sep 2026 09:20:17 GMT</pubDate>
            <atom:updated>2026-09-25T09:45:15.716Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Permission, provisional authorization, and local notifications for a habit tracker: Done and Snooze buttons, the 64-notification limit, and interruption levels.</em></p><p><em>This is Part 1 of </em><a href="https://medium.com/@saadsherif02/ios-notifications-end-to-end-part-0-which-notification-do-you-need-cf3057ad7b9e"><em>iOS Notifications, End to End</em></a><em>. New to the series? Start with Part 0, the map.</em></p><p>Local notifications are the best place to start. They need no server, no Apple Developer account and no certificates. They still teach you most of what you’ll use later: permission, categories, actions, the delegate, and how iOS decides what’s worth interrupting someone for.</p><p>We’re building the Habits tab of NotifyLab. By the end you’ll have:</p><ul><li>A permission prompt shown at the moment it makes sense, not at launch</li><li>Daily reminders that stay under iOS’s hidden limit of 64</li><li>Done, Snooze 10 min and Add a note buttons that work without opening the app</li><li>Three test buttons that show the difference between <em>passive</em>, <em>active</em> and <em>time-sensitive</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_6CsQSSdmWGjTaCJUv5rQ.png" /></figure><blockquote><em>Code: </em><em>HabitScheduler.swift, </em><em>NotificationCategories.swift and </em><em>NotificationRouter.swift in the </em><a href="https://github.com/Sa3doola/NotifyLab"><em>NotifyLab repo</em></a><em>. Everything below runs in the Simulator.</em></blockquote><h3>The anatomy of a local notification</h3><p>A local notification is three objects handed to one center:</p><pre>UNMutableNotificationContent   what it says: title, body, sound, category, interruption level<br>+ UNNotificationTrigger        when: after N seconds, at a calendar date, or at a location<br>= UNNotificationRequest        with an identifier you choose<br>→ UNUserNotificationCenter.add(request)</pre><p>The identifier matters more than it looks. Adding a request with an existing identifier replaces it. That’s how you update or cancel a reminder later, so make identifiers stable and meaningful (habit.&lt;id&gt;.2026-09-24), not random.</p><h3>Step 1: Ask at the right moment</h3><p>iOS shows the permission prompt once. If the user taps <em>Don’t Allow</em>, the only way back is the Settings app. So the prompt is the most valuable screen in your notification setup. Don’t spend it at launch, before the user knows why you’re asking.</p><p>In NotifyLab, the Habits tab shows a <em>“Turn on reminders”</em> row next to the habits themselves. That’s the moment the prompt makes sense:</p><pre>@MainActor @Observable<br>final class NotificationPermission {<br>    private(set) var status: UNAuthorizationStatus = .notDetermined<br>    private let center = UNUserNotificationCenter.current()<br><br>    @discardableResult<br>    func requestFull() async -&gt; Bool {<br>        let granted = (try? await center.requestAuthorization(options: [.alert, .sound, .badge])) ?? false<br>        await refresh()<br>        return granted<br>    }<br><br>    func refresh() async {<br>        let settings = await center.notificationSettings()<br>        status = settings.authorizationStatus<br>        // …plus alertSetting, lockScreenSetting, timeSensitiveSetting, scheduledDeliverySetting…<br>    }<br>}</pre><p>Two rules that save you bug reports:</p><ul><li>Re-read the settings every time the app becomes active. Users change them in Settings at any time. NotifyLab calls refresh()from scenePhase == .active.</li><li>After a denial, don’t nag. Deep-link instead:</li></ul><pre>if let url = URL(string: UIApplication.openNotificationSettingsURLString) {<br>    UIApplication.shared.open(url)   // opens *your app&#39;s* notification settings (iOS 16+)<br>}</pre><p>On my iPhone this opens NotifyLab’s own notification page. On the iOS 27 Simulator it opened the main Settings page instead, so check this one on a device.</p><h3>Step 2: Or don’t ask at all (provisional authorization)</h3><p>Add .provisional and iOS skips the prompt entirely:</p><pre>try await center.requestAuthorization(options: [.alert, .sound, .badge, .provisional])</pre><p>Your notifications then arrive <em>quietly</em>: no banner, no sound, no lock screen. They go straight to Notification Center, with two buttons: Keepand Turn Off. The user decides after seeing real value, not a hypothetical one.</p><p>authorizationStatus becomes .provisional. You can still ask for full permission later; NotifyLab&#39;s Status tab shows <em>&quot;Ask for permission&quot;</em> while the status is provisional.</p><p>When to use it: apps where the first notification proves its own worth, like a weekly summary or a “your report is ready”. When not to:anything time-critical, because a quiet notification is an easily missed one.</p><h3>Step 3: Register the buttons (categories and actions)</h3><p>Buttons belong to a category. You register categories once, at launch, before any notification can arrive:</p><pre>enum NotificationCategories {<br>    static func register() {<br>        let done = UNNotificationAction(<br>            identifier: ActionID.habitDone, title: &quot;Done&quot;,<br>            options: [], icon: UNNotificationActionIcon(systemImageName: &quot;checkmark.circle&quot;))<br>        let snooze = UNNotificationAction(<br>            identifier: ActionID.habitSnooze, title: &quot;Snooze 10 min&quot;,<br>            options: [], icon: UNNotificationActionIcon(systemImageName: &quot;clock.arrow.circlepath&quot;))<br>        let note = UNTextInputNotificationAction(<br>            identifier: ActionID.habitNote, title: &quot;Add a note&quot;,<br>            options: [], icon: UNNotificationActionIcon(systemImageName: &quot;square.and.pencil&quot;),<br>            textInputButtonTitle: &quot;Save&quot;, textInputPlaceholder: &quot;How did it go?&quot;)<br><br>        let habit = UNNotificationCategory(<br>            identifier: CategoryID.habit,<br>            actions: [done, snooze, note],<br>            intentIdentifiers: [],<br>            options: [.customDismissAction])   // also tell us when it&#39;s swiped away<br><br>        UNUserNotificationCenter.current().setNotificationCategories([habit /*, order, message */])<br>    }<br>}</pre><ul><li>options: [] means the action runs in the background. The app wakes briefly and the notification closes, but the app doesn&#39;t open. Use .foreground when the action needs the UI (like &quot;Track order&quot; in Part 5).</li><li>A notification picks its buttons with content.categoryIdentifier = &quot;HABIT&quot;. For remote pushes, it&#39;s &quot;category&quot;: &quot;HABIT&quot; in the payload. Same buttons, same handler.</li></ul><h3>Step 4: Schedule a reminder</h3><pre>let content = UNMutableNotificationContent()<br>content.title = habit.name<br>content.body = &quot;Keep your \(streak)-day streak going.&quot;<br>content.sound = .default<br>content.categoryIdentifier = CategoryID.habit          // Done / Snooze / Note<br>content.threadIdentifier = &quot;habit-\(habit.id)&quot;         // groups this habit&#39;s reminders<br>content.interruptionLevel = .active                    // more in Step 7<br>content.userInfo = [&quot;habitId&quot;: habit.id.uuidString]    // for the handler<br><br>let parts = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: fireDate)<br>let trigger = UNCalendarNotificationTrigger(dateMatching: parts, repeats: false)<br>let request = UNNotificationRequest(identifier: &quot;habit.\(habit.id).\(dayKey)&quot;, content: content, trigger: trigger)<br><br>try await UNUserNotificationCenter.current().add(request)</pre><p>The tempting shortcut is one repeating trigger per habit:</p><pre>UNCalendarNotificationTrigger(dateMatching: DateComponents(hour: 8, minute: 0), repeats: true)</pre><p>It works in a demo. In a real habit app it has one fatal flaw: a repeating trigger can’t skip a day. The user ticks “Stretch” at 7:40, and the 8:00 reminder still fires. That’s how you teach people to ignore your notifications.</p><h3>Step 5: The limit nobody mentions, 64</h3><p>The fix is one request per day, so you can remove today’s when the habit is done. That runs straight into a limit: iOS keeps at most 64 pending local notifications per app. It keeps the 64 that fire soonest and silently drops the rest, with no error. Five daily habits, two weeks ahead, is already 70.</p><p>NotifyLab uses a rolling window:</p><blockquote><em>Every time the app runs, schedule the next occurrences of every habit (up to 14 days ahead, capped at 60 requests), soonest first. Skip today’s reminder if the habit is already done.</em></blockquote><pre>func replan() async {<br>    // 1. Remove what we scheduled last time<br>    let old = await center.pendingNotificationRequests()<br>        .map(\.identifier)<br>        .filter { $0.hasPrefix(&quot;habit.&quot;) &amp;&amp; !$0.hasSuffix(&quot;.snooze&quot;) }<br>    center.removePendingNotificationRequests(withIdentifiers: old)<br><br>    // 2. Next occurrences, soonest first, within budget (60 of 64: 4 left for snoozes &amp; tests)<br>    let upcoming = upcomingOccurrences().sorted { $0.date &lt; $1.date }<br>    let planned = upcoming.prefix(60)<br>    droppedCount = upcoming.count - planned.count<br><br>    // 3. Schedule<br>    for occurrence in planned {<br>        try? await center.add(request(for: occurrence.habit, at: occurrence.date))<br>    }<br>}</pre><p>replan() runs on every launch and every time the app becomes active, and whenever a habit is added, deleted or marked done. With the three demo habits it schedules up to 38 of 64 (two weeks of three habits, one of them weekdays only), and the Habits tab shows the count.</p><p>The trade-off, stated honestly: if the user doesn’t open the app for 14 days, reminders stop. For a habit app that’s arguably correct. If it isn’t for yours, make the last scheduled reminder say so (“Open NotifyLab to keep your reminders coming”), or top up the window from a background task.</p><p>When the user marks a habit done, we also clean up what’s already on screen:</p><pre>let delivered = await center.deliveredNotifications()<br>    .map(\.request.identifier)<br>    .filter { $0.hasPrefix(&quot;habit.\(habitID)&quot;) }<br>center.removeDeliveredNotifications(withIdentifiers: delivered)</pre><h3>Step 6: Handle taps and buttons (the delegate)</h3><p>One object answers two questions for every notification, local or remote:</p><ul><li>“The app is open. Should I show this?” → willPresent</li><li>“The user tapped it or a button. What now?” → didReceive</li></ul><p>Set it before application(_:didFinishLaunchingWithOptions:) returns. Otherwise the tap that <em>launched</em> the app is lost:</p><pre>func application(_ application: UIApplication,<br>                 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -&gt; Bool {<br>    UNUserNotificationCenter.current().delegate = model.router<br>    NotificationCategories.register()<br>    // …<br>    return true<br>}</pre><p>In a SwiftUI app, that’s what @UIApplicationDelegateAdaptor(AppDelegate.self) is for.</p><h3>The Swift 6 detail (and the crash I shipped in my first draft)</h3><p>When you write the async versions of these delegate methods, iOS still passes a hidden completion handler, and Swift calls it for youwhen your method returns. iOS requires that call on the main thread.</p><p>My first draft marked the methods nonisolated. It compiled with zero warnings, and willPresent even worked. Then tapping Call driver on a real iPhone crashed:</p><pre>Task 66: &quot;Call must be made on main thread&quot;</pre><p>A nonisolated async method finishes on a background executor, so Swift called iOS&#39;s completion handler from there. The fix is one word in the right place: make the conformance main-actor-isolated (Swift 6.2+), so both methods run and finish on the main actor:</p><pre>extension NotificationRouter: @MainActor UNUserNotificationCenterDelegate {<br><br>    func userNotificationCenter(_ center: UNUserNotificationCenter,<br>                                willPresent notification: UNNotification) async -&gt; UNNotificationPresentationOptions {<br>        presentInForeground(NotificationEvent(notification.request))   // [.banner, .list, .sound, .badge]<br>    }<br><br>    func userNotificationCenter(_ center: UNUserNotificationCenter,<br>                                didReceive response: UNNotificationResponse) async {<br>        let typed = (response as? UNTextInputNotificationResponse)?.userText<br>        await handle(NotificationEvent(response.notification.request,<br>                                       actionID: response.actionIdentifier,<br>                                       typedText: typed))<br>    }<br>}</pre><p>NotificationEvent is a small Sendable struct that copies what we need out of userInfo (which isn&#39;t Sendable), so the handler never holds on to notification objects:</p><pre>struct NotificationEvent: Sendable {<br>    let actionID: String<br>    let categoryID: String<br>    let title: String<br>    let habitID: UUID?<br>    let typedText: String?<br>    // init(_ request:actionID:typedText:) copies the values out of userInfo<br>}</pre><blockquote><em>Lesson: “it compiles under Swift 6” is not “it’s correct at runtime”. Test every notification path, including tap, each button, and dismiss, on a real device before you ship.</em></blockquote><p>And the handler is a plain switch on the button&#39;s identifier:</p><pre>    /// The user tapped the notification, a button, or dismissed it.<br>    func handle(_ event: NotificationEvent) async {<br>        switch event.actionID {<br>        case ActionID.habitDone:<br>            guard let id = event.habitID else { return }<br>            await habits.markDone(id)<br>            EventLog.add(&quot;Habit done from notification&quot;, source: &quot;app&quot;)<br><br>        case ActionID.habitSnooze:<br>            guard let id = event.habitID else { return }<br>            await habits.snooze(id)<br>            EventLog.add(&quot;Habit snoozed for 10 min&quot;, source: &quot;app&quot;)<br><br>        case ActionID.habitNote:<br>            EventLog.add(&quot;Habit note: \(event.typedText ?? &quot;&quot;)&quot;, source: &quot;app&quot;)<br><br>        // … the order and message buttons (Parts 4 and 5)<br><br>        case UNNotificationDismissActionIdentifier:<br>            EventLog.add(&quot;Dismissed: \(event.title)&quot;, source: &quot;app&quot;)<br><br>        default:<br>            // Plain tap, or &quot;Track order&quot;: deep-link to the right screen.<br>            // … (a habit reminder opens the Habits tab; Part 4 shows this branch)<br>        }<br>    }</pre><p>The dismiss case only fires because the category has .customDismissAction. Without it, iOS doesn&#39;t tell you the user swiped the notification away.</p><blockquote><em>Without </em><em>willPresent, notifications that arrive while your app is open show nothing. This is the most common &quot;notifications don&#39;t work&quot; report in development.</em></blockquote><h3>Step 7: Interruption levels (how loud to be)</h3><p>Since iOS 15, every notification carries an interruption level. It’s the difference between a tap on the shoulder and a fire alarm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UKRZoozzA7SzD6rSoDBgcA.png" /><figcaption><em>The four interruption levels. Pick the lowest one that does the job.</em></figcaption></figure><p>For local notifications it’s one line:</p><pre>content.interruptionLevel = .timeSensitive<br>content.relevanceScore = 0.6   // 0…1, orders your notifications inside the Scheduled Summary</pre><p>In NotifyLab, the Habits tab has three buttons that each fire a sample in 5 seconds. Tap one, lock the Simulator (⌘L), and watch the difference. Passive never lights up the screen. Time-sensitive is labeled TIME SENSITIVE on the lock screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2YC0vP2LRkByka0cdI9G-g.png" /><figcaption><em>The TIME SENSITIVE label, here on an order update you’ll send in Part 4. The three Active samples below share a thread ID, so iOS groups them.</em></figcaption></figure><p>Pick the lowest level that still does the job. Users can switch time-sensitive off per app. Once they’ve learned your “urgent” isn’t urgent, they will.</p><h3>Test it</h3><ol><li>Run NotifyLab on any iOS 17+ Simulator and open the Habits tab.</li><li>Tap Turn on reminders → Allow. The list header shows <em>Scheduled: 38 of 64</em>, or a little less late in the day, because reminders that already passed today are skipped.</li><li>Tap Active: arrives in 5 s, then press ⌘⇧H to go to the home screen. The banner arrives.</li><li>Pull down Notification Center and long-press the reminder. You’ll see Done, Snooze 10 min, Add a note.</li><li>Tap Done. The app doesn’t open. Now open it yourself: the samples are linked to the first habit, so Stretch is ticked for today.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lYYew8VJ-FImlbNcAVEGyQ.png" /><figcaption><em>The test samples use the same HABIT category, so they get the same three buttons.</em></figcaption></figure><p>Watch iOS schedule everything live:</p><pre>xcrun simctl spawn booted log stream --level debug \<br>  --predicate &#39;subsystem == &quot;com.apple.UserNotifications&quot; AND category == &quot;LocalNotifications&quot;&#39;</pre><p>You’ll see one line per request, like <em>“Notification … has a trigger date 2026–10–01 08:00”</em>, and <em>“Scheduling persistent timer for next local notification”</em>.</p><h3>Production notes</h3><ul><li>Set the delegate before didFinishLaunching returns, and register categories there too.</li><li>Don’t ask at launch. Ask next to the feature. Consider provisional for low-stakes content.</li><li>Re-read settings on every foreground. Handle .denied with a deep link to Settings, not another prompt.</li><li>Stay under 64. Count your pending requests, and use a rolling window for anything calendar-based.</li><li>Stable identifiers. Re-adding the same identifier replaces the old request. That’s your update and cancel mechanism.</li><li>Time zones: DateComponents(hour: 8) without a time zone means <em>8:00 wherever the user is now</em>, which is right for habits. For a fixed moment (a webinar), include the time zone or use a full Date.</li><li>Repeating UNTimeIntervalNotificationTrigger must be ≥ 60 seconds, or the app crashes when creating it.</li><li>Clean up. Remove delivered notifications when they’re no longer true, and reset the badge (setBadgeCount(0)) when the user opens the app.</li><li>Lock-screen privacy. Set hiddenPreviewsBodyPlaceholder on categories whose body might be personal.</li></ul><p>Next: <a href="https://medium.com/@saadsherif02/ios-notifications-end-to-end-part-2-wiring-up-push-b1787b828cdb">Part 2</a>, Wiring up push. We leave the device and set up what remote notifications need: the App ID, capabilities, the entitlements file, and the .p8 key that your server (or Firebase) uses to talk to APNs, with every screenshot along the way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8800c253ae2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Notifications, End to End — Part 0: Which Notification Do You Need?]]></title>
            <link>https://medium.com/@saadsherif02/ios-notifications-end-to-end-part-0-which-notification-do-you-need-cf3057ad7b9e?source=rss-272a2ec2e25d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf3057ad7b9e</guid>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Saad Sherif]]></dc:creator>
            <pubDate>Fri, 25 Sep 2026 08:53:11 GMT</pubDate>
            <atom:updated>2026-09-25T09:22:50.683Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8bF3L8CoI2yD1Z7q-chQqA.png" /></figure><p><em>A map of every notification an iOS app ships: habit reminders, order updates, silent syncs, VoIP calls, rich notifications and messages that show the sender’s face. Plus the one demo app we’ll build across this series.</em></p><p>If you asked me for the most common notification problem you’ll run into, I’d say it’s this one: the notification never shows up.</p><p>The idea for this series came from <a href="https://www.youtube.com/watch?v=aXbnjpnnBjA&amp;t=2625s">a YouTube video</a>. Two iOS developers, <a href="https://www.linkedin.com/in/menaim/">Ahmed Menaim</a> (senior iOS developer) and <a href="https://www.linkedin.com/in/mostafanafie/">Mostafa Nafie</a> (staff iOS engineer, <a href="https://www.nafie.dev/">nafie.dev</a>), sat down for a podcast-style talk about notifications and went deep into the details. It inspired me to do the same in writing: document everything, as a way to learn it properly and to share what I learned.</p><p>This series is the guide I wish I’d had: every notification type on iOS, the setup behind it, how it actually travels from your server to the screen, and what quietly stops it on the way. Each part ends with something you can run.</p><p>This first part is the map.</p><h3>The six kinds of notification</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*18X7oqNk5V09GUCXEnO2ew.png" /><figcaption><em>The six kinds of notification, side by side.</em></figcaption></figure><p>Three things surprise people in this table:</p><ol><li>A remote push is not one thing. The same pipe (APNs) carries an alert, a silent wake-up, and a VoIP call. They behave completely differently, and one HTTP header, apns-push-type, says which one you&#39;re sending. (A VoIP call also needs its own token.)</li><li>“Rich” and “communication” aren’t separate kinds of push. Both are ordinary alerts with mutable-content: 1. Your Service Extension adds a photo to the first, and turns the second into a message from a person, with their face where your app icon would be.</li><li>Some notifications need no permission at all.</li></ol><blockquote><em>“Can I send notifications without asking for permission?” Yes, in three honest ways.</em></blockquote><ul><li>Provisional authorization (iOS 12+) shows no prompt and delivers quietly to Notification Center with <em>Keep</em> and <em>Turn Off</em> buttons.</li><li>Background pushes need no permission because they show nothing.</li><li>VoIP pushes need no permission, but every one must show the system call screen.</li></ul><p>And you can always get a device token without permission. Asking and registering are two separate calls.</p><h3>How a remote push travels, from start to end</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A9ojUajepGhUak4ISCk30A.png" /><figcaption><em>Figure 2: two loops, not one pipe.</em></figcaption></figure><p>Most tutorials draw this as a straight line: server → Apple → phone. In production it’s two loops.</p><p>Loop 1: Register (every launch). The app calls registerForRemoteNotifications(). iOS talks to APNs and hands you a device token. (Asking for permission is a separate step. It decides what the user sees, not whether you get a token.) If you use Firebase, you pass that token to the FCM SDK and get an FCM token back. Both go to your server, which saves them with a lastSeenAt timestamp.</p><p>Loop 2: Send (every event). Something happens: <em>order #1042 shipped</em>. Your server sends to FCM (HTTP v1), and FCM calls APNs with the key you uploaded. Or your server calls APNs directly. APNs delivers to the device, or keeps it if the device is offline, but only the newest one per app. iOS runs your Service Extension, then decides whether to show it at all, based on permission, Focus and the interruption level. When the user taps, your app routes to the right screen.</p><p>Every bug report you’ll ever get lives somewhere on that picture. Part 7 walks through it gate by gate.</p><h3>What we’ll build: NotifyLab</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sI8COPm5tsvwLXmVudw6VA.png" /><figcaption><em>NotifyLab’s Status tab. The five tabs sit at the bottom.</em></figcaption></figure><p>One SwiftUI app, five tabs, each a real product scenario:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Srtact2kr7I95682_2Lxqg.png" /></figure><p>It comes with a test kit, so every part ends with <em>“now run this”</em>:</p><ul><li>payloads/*.apns: drag them onto the Simulator, or run xcrun simctl push.</li><li>tools/apns.sh: the exact curl request your server would make.</li><li>tools/fcm.mjs: the same thing through Firebase HTTP v1.</li><li>tools/registry-server.mjs: a 100-line token server that deletes dead tokens.</li><li>A Postman collection, and the Push Notifications Console walkthrough.</li></ul><p>The code is on GitHub: <a href="https://github.com/Sa3doola/NotifyLab">NotifyLab</a>. Clone it, open NotifyLab.xcodeproj and run it on any iOS 17+ Simulator. You don&#39;t need an Apple Developer account until Part 2.</p><h3>The series</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tW9F4TlnyA_4ebSiyixQPA.png" /><figcaption><em>The series at a glance.</em></figcaption></figure><p>The repo holds the finished app. Each part names the files it covers, so you can read the real code next to the article.</p><p>Next: <a href="https://medium.com/@saadsherif02/ios-notifications-end-to-end-part-1-ask-well-remind-well-c8800c253ae2">Part 1</a>, Ask well, remind well. We’ll ask for permission at the moment it makes sense, schedule habit reminders that respect the 64-notification limit, and add Done and Snooze buttons that work without opening the app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf3057ad7b9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Universal Links in iOS: how they actually work, and how to stop debugging them blind]]></title>
            <link>https://medium.com/@saadsherif02/universal-links-in-ios-how-they-actually-work-and-how-to-stop-debugging-them-blind-b71ff7e1b169?source=rss-272a2ec2e25d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b71ff7e1b169</guid>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[deeplinktutorial]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios-universal-link]]></category>
            <dc:creator><![CDATA[Saad Sherif]]></dc:creator>
            <pubDate>Sun, 20 Sep 2026 14:04:49 GMT</pubDate>
            <atom:updated>2026-09-20T14:04:49.952Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m-PHNXYFL4bKcdNtufpg7Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YG-jreDNpwL9RRlSsSfjuw.png" /></figure><p>If you’ve ever shipped a “share this product” feature or a marketing deep link, you’ve run into Universal Links — the mechanism that lets a plain https:// URL open your app directly instead of dumping the user into Safari. They feel like magic when they work and like a black box when they don&#39;t. Here&#39;s the full picture: routing, the underlying file format, Apple&#39;s caching layer, and both the UIKit and SwiftUI ways of handling the result.</p><h4>The core idea</h4><p>A Universal Link is just a normal web URL. The difference is that iOS has a way to know, ahead of time, that certain URL patterns belong to your app rather than to the open web. That mapping lives in a single JSON file: the <strong>Apple App Site Association (AASA) file</strong>.</p><p>When someone taps a link, iOS checks whether it matches your app’s registered AASA patterns, then whether your app is installed. If it is, the link opens straight into the app with the destination handled as a deep link. If it isn’t, the URL behaves like any other web page in Safari — no forced App Store redirect, no broken experience for users who haven’t installed yet.</p><h4>Setting it up</h4><p><strong>1. Create the AASA file.</strong> It’s a JSON file named exactly apple-app-site-association, with no file extension:</p><pre><br>  &quot;applinks&quot;: {<br>    &quot;apps&quot;: [],<br>    &quot;details&quot;: [<br>      {<br>        &quot;appID&quot;: &quot;TeamId.com.company.myapp&quot;,<br>        &quot;paths&quot;: [&quot;*&quot;]<br>      }<br>    ]<br>  }<br>}</pre><p>appID combines your Apple Team ID and bundle identifier. paths is the array of URL paths your app should intercept.</p><p><strong>2. Register the domain in Xcode.</strong> Under your target’s <em>Signing &amp; Capabilities</em>, add <strong>Associated Domains</strong>, then add an entry like applinks:yourdomain.com.</p><p><strong>3. Host the file correctly</strong>, at:</p><pre>https://&lt;your-domain&gt;/.well-known/apple-app-site-association</pre><p>Requirements: HTTPS, no file extension, under 128 KB, and served with Content-Type: application/json. On Apache:</p><pre>&lt;Files &quot;apple-app-site-association&quot;&gt;<br>  Header set Content-Type &quot;application/json&quot;<br>&lt;/Files&gt;</pre><p>On Nginx:</p><pre>location = /apple-app-site-association {<br>  default_type application/json;<br>  ...<br>}</pre><h4>The part most people miss: Apple’s CDN cache</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tLjoSD9NV88DRUXWBIV7Zg.png" /></figure><p>Your device doesn’t read the AASA file from your server every time a link is tapped. The first time your app is installed, Apple’s CDN fetches your file and holds onto it — and it can take up to a day for the CDN to pick up a domain’s file for the first time, with devices then checking back for updates roughly once a week after the app is installed. <a href="https://zenn.dev/fujishiro/scraps/f5986bf177aa93">zenn</a></p><p>How long the CDN holds onto a given version afterward comes down to your own server’s cache headers: the Cache-Control response header determines how long both browsers and the CDN treat a version as valid, and Apple periodically re-crawls your server to check for changes, but if your headers don’t clearly signal that something changed, the CDN may keep serving the old copy. Because Apple’s edge network has locations worldwide, a user in one region can see an updated file before a user elsewhere does.</p><p>Two things make this debuggable instead of mysterious:</p><ul><li>You can see exactly what Apple currently has cached by fetching https://app-site-association.cdn-apple.com/a/v1/&lt;yourdomain&gt; directly — this endpoint returns the cached content for that domain. <a href="https://github.com/jbranchaud/til/blob/master/devops/check-for-cached-site-association-file-for-ios.md">GitHub</a></li><li>Appending any throwaway query string to that same URL forces Apple’s CDN to re-request the file from your origin, which is the fastest way to confirm the <em>next</em> version will be correct once the cache actually rolls over — it doesn’t force devices to pick it up any faster, but it tells you your server-side fix is good. <a href="https://digitalbunker.dev/apple-app-site-association/">Digital Bunker</a></li></ul><p>Practically: deleting and reinstalling the app is the reliable way to force a fresh fetch on your own test device, since App Store and TestFlight builds don’t offer another way to trigger it. <a href="https://codemia.io/knowledge-hub/path/apple-app-site-association_file_is_not_fetched_from_server_but_cached_at_apple">Codemia</a></p><h4>Debugging it properly</h4><p>Beyond the CDN check above, a few standard tools help:</p><ul><li>A <strong>JSON validator</strong> (like <a href="https://jsonlint.com/">JSONLint</a>) to confirm the file itself is well-formed</li><li>A <a href="https://yurl.chayev.com/ios-results"><strong>universal link validator</strong></a> to confirm your domain and paths resolve as expected</li><li><a href="https://branch.io/resources/aasa-validator/"><strong>Branch’s</strong></a> validator, which many teams already use if they’re on that platform</li></ul><p>For device-level debugging: go to <em>Settings → Privacy &amp; Security → Analytics &amp; Improvements → Analytics Data</em>, find a sysdiagnose file, share it to your Mac, and unzip it. Inside, swcutil_show.txt lists every app-domain association currently cached on that device, along with <strong>last checked</strong> and <strong>next check</strong> timestamps — telling you definitively whether your AASA file was fetched and what iOS believes it says.</p><h4>How to generate a sysdiagnose on iPhone</h4><p>There are two ways to trigger it, depending on whether you have working physical buttons.</p><p><strong>Method 1 — button combination (fastest)</strong></p><ol><li>Press and hold <strong>both volume buttons and the side button</strong> at the same time, for 1 to 1.5 seconds.</li><li>Release all three together. You’ll feel a short vibration — that’s your confirmation it started.</li><li>If you keep holding past that point, iOS starts a countdown toward the SOS emergency-call screen. If you see that appear, just release the buttons — you’ve already held them long enough to trigger the sysdiagnose.</li><li>Reproduce the universal link issue on the device now, while the diagnostic is capturing.</li></ol><p><strong>Method 2 — AssistiveTouch (if physical buttons aren’t usable)</strong></p><ol><li>Go to <em>Settings → Accessibility → Touch → AssistiveTouch</em> and turn it on.</li><li>Tap <strong>Customize Top Level Menu</strong>, tap the <strong>+</strong> to add a function, select <strong>Analytics</strong>, then confirm.</li><li>Reproduce the issue.</li><li>Tap the AssistiveTouch button, then tap <strong>Analytics</strong>. A banner will confirm “Gathering analytics” and later “Successfully completed gathering analytics.”</li></ol><p><strong>Finding and exporting the file</strong></p><ol><li>The capture takes anywhere from a couple of minutes up to about 10 — it isn’t instant.</li><li>Go to <em>Settings → Privacy &amp; Security → Analytics &amp; Improvements → Analytics Data</em>.</li><li>Search for sysdiagnose — you&#39;ll get a long list, sorted so the most recent is easy to spot by its timestamp.</li><li>Tap it, then use the <strong>share icon</strong> in the top right to AirDrop it to your Mac (the file is large, so AirDrop is far more practical than email).</li></ol><p>Once it’s on your Mac, unzip it and open swcutil_show.txt — search for your app ID and you&#39;ll find the exact domain association iOS has cached, along with its last-checked and next-check times, which is what you actually want when confirming whether an AASA change has taken effect on that device.</p><p>A reliable test sequence: delete the app, reinstall it (forcing a fresh AASA fetch), then paste the URL into Safari. If everything’s configured right, Safari detects the domain and routes into your app rather than rendering the page.</p><h4>Handling the link — two ways</h4><p><strong>UIKit</strong> requires you to branch on app state manually. In AppDelegate:</p><pre>func application(_ application: UIApplication, continue userActivity: NSUserActivity,<br>                  restorationHandler: @escaping ([UIUserActivityRestoring]?) -&gt; Void) -&gt; Bool { }</pre><p>In SceneDelegate, terminated state (build the window yourself, then route):</p><pre>func scene(_ scene: UIScene, willConnectTo session: UISceneSession,<br>           options connectionOptions: UIScene.ConnectionOptions) {<br>    guard let windowScene = (scene as? UIWindowScene) else { return }<br>    guard let userActivity = connectionOptions.userActivities.first else { return }<br>    window = UIWindow(frame: UIScreen.main.bounds)<br>    window?.windowScene = windowScene<br>    window?.rootViewController = AppTabBarController.create()<br>    window?.makeKeyAndVisible()<br>    if let productVC = handle(userActivity) {<br>        guard let tabBar = window?.rootViewController as? AppTabBarController else { return }<br>        guard let nav = tabBar.selectedViewController as? BaseNav else { return }<br>        nav.pushViewController(productVC, animated: true)<br>    }<br>}</pre><p>And background state (window already exists):</p><pre>func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {<br>    if let productVC = handle(userActivity) {<br>        guard let windowScene = scene as? UIWindowScene?,<br>              let window = windowScene?.keyWindow,<br>              let root = window.rootViewController else { return }<br>        if let tabBar = root as? AppTabBarController {<br>            guard let nav = tabBar.selectedViewController as? BaseNav else { return }<br>            nav.pushViewController(productVC, animated: true)<br>        } else if let authNav = root as? AuthNav {<br>            authNav.pushViewController(productVC, animated: true)<br>        }<br>    }<br>}</pre><p>Parsing the path with regex:</p><pre>private func getId(pathString: String) -&gt; (Int?, String?)? {<br>    let pattern = &quot;/product/(\\d+)/(.*)&quot;<br>    let secondPattern = &quot;/product-share/(\\d+)/(.*)&quot;<br>    if let data = getIdFromExpression(pattern: pattern, pathString: pathString) {<br>        return data<br>    } else if let validateData = getIdFromExpression(pattern: secondPattern, pathString: pathString) {<br>        return validateData<br>    }<br>    return nil<br>}<br><br>private func getIdFromExpression(pattern: String, pathString: String) -&gt; (Int?, String?)? {<br>    guard let regex = try? NSRegularExpression(pattern: pattern) else { return nil }<br>    let nsString = pathString as NSString<br>    guard let match = regex.matches(in: pathString, range: NSRange(location: 0, length: nsString.length)).first,<br>          let numberRange = Range(match.range(at: 1), in: pathString),<br>          let nameRange = Range(match.range(at: 2), in: pathString) else { return nil }<br>    return (Int(pathString[numberRange]), String(pathString[nameRange]))<br>}<br><br>private func handle(_ userActivity: NSUserActivity) -&gt; ProductDetailsVC? {<br>    guard userActivity.activityType == NSUserActivityTypeBrowsingWeb,<br>          let incomingURL = userActivity.webpageURL,<br>          let components = NSURLComponents(url: incomingURL, resolvingAgainstBaseURL: true),<br>          let path = components.path,<br>          let id = getId(pathString: path)?.0,<br>          let referralCode = getId(pathString: path)?.1 else { return nil }<br>    return ProductDetailsVC.create(id: id, referralCode: referralCode)<br>}</pre><p>Generating the share link:</p><pre>private func presentShareSheet() {<br>    let urlString = &quot;https://yourdomain/product/\(purchasedProduct.id)&quot;<br>    guard let link = URL(string: urlString) else { return }<br>    let activityController = UIActivityViewController(activityItems: [link], applicationActivities: nil)<br>    present(activityController, animated: true)<br>}</pre><p><strong>SwiftUI</strong> collapses all of that lifecycle branching into one entry point. Register both onOpenURL (custom schemes, and universal links in most cases) and onContinueUserActivity(NSUserActivityTypeBrowsingWeb) — Apple&#39;s explicit, documented path for universal links specifically, and the one that also hands you the full NSUserActivity if you ever need referrerURL or userInfo:</p><pre>@main<br>struct MyApp: App {<br>    @StateObject private var router = Router()<br><br>    var body: some Scene {<br>        WindowGroup {<br>            NavigationStack(path: $router.path) {<br>                HomeView()<br>                    .navigationDestination(for: Route.self, destination: router.destination)<br>            }<br>            .environmentObject(router)<br>            .onOpenURL { url in<br>                router.handle(url: url)<br>            }<br>            .onContinueUserActivity(NSUserActivityTypeBrowsingWeb) { userActivity in<br>                guard let url = userActivity.webpageURL else { return }<br>                router.handle(url: url)<br>            }<br>        }<br>    }<br>}</pre><p>Model the destination as a typed enum instead of passing raw URLs around:</p><pre>enum Route: Hashable {<br>    case productDetails(id: Int, referralCode: String?)<br>    case category(slug: String)<br>    case home<br>}</pre><p><strong>DeepLinkResolver</strong> — a pure function turning a URL into a Route, more idiomatic than regex and easy to extend:</p><pre>enum DeepLinkResolver {<br>    static func resolve(url: URL) -&gt; Route? {<br>        guard let components = URLComponents(url: url, resolvingAgainstBaseURL: true) else {<br>            return nil<br>        }<br>        let parts = components.path.split(separator: &quot;/&quot;).map(String.init)<br><br>        switch parts.first {<br>        case &quot;product&quot;, &quot;product-share&quot;:<br>            guard parts.count &gt;= 2, let id = Int(parts[1]) else { return nil }<br>            let referralCode = parts.count &gt;= 3 ? parts[2] : nil<br>            return .productDetails(id: id, referralCode: referralCode)<br><br>        case &quot;category&quot;:<br>            guard parts.count &gt;= 2 else { return nil }<br>            return .category(slug: parts[1])<br><br>        default:<br>            return nil<br>        }<br>    }<br>}</pre><p><strong>Router</strong> — owns navigation state and is the single place turning a Route into a destination view. It doesn&#39;t matter whether the call came from a deep link, a button, or a push notification:</p><pre>final class Router: ObservableObject {<br>    @Published var path = NavigationPath()<br><br>    func handle(url: URL) {<br>        guard let route = DeepLinkResolver.resolve(url: url) else { return }<br>        navigate(to: route)<br>    }<br><br>    func navigate(to route: Route) {<br>        path.append(route)<br>    }<br><br>    func popToRoot() {<br>        path.removeLast(path.count)<br>    }<br><br>    @ViewBuilder<br>    func destination(for route: Route) -&gt; some View {<br>        switch route {<br>        case .productDetails(let id, let referralCode):<br>            ProductDetailsView(id: id, referralCode: referralCode)<br>        case .category(let slug):<br>            CategoryView(slug: slug)<br>        case .home:<br>            HomeView()<br>        }<br>    }<br>}</pre><p>This buys you three things the UIKit version doesn’t have for free: DeepLinkResolver.resolve(url:) is unit-testable with no view hierarchy involved, every navigation trigger in the app funnels through the same navigate(to:) call, and there&#39;s no manual &quot;is the window nil&quot; branching for cold start — NavigationStack just reacts to router.path once the view exists.</p><h4>Quick debugging checklist</h4><ol><li>Inspect the entitlement: applinks:yourdomain.com</li><li>Open the AASA URL directly, and check https://app-site-association.cdn-apple.com/a/v1/&lt;domain&gt; to see what&#39;s actually cached</li><li>Validate the JSON and the matching rule</li><li>Confirm Team ID + bundle ID against the AASA appID</li><li>Test one URL that should match, and one that shouldn’t</li><li>Reinstall the app to force a fresh fetch</li><li>Pull a sysdiagnose and check swcutil_show.txt for the cached association and its next-check time</li><li>Verify the exact URL path, scheme, and any redirects along the way</li></ol><h4>Takeaway</h4><p>Universal Links look deceptively simple — “just make a URL open the app” — but reliability comes down to a handful of pieces staying in sync: a valid, correctly-served AASA file, the Associated Domains entitlement, and correct continuation handling on the app side. The CDN caching layer is the detail most people never learn about until they’ve lost a day to it — know that it exists, know how to peek at what’s actually cached, and most “it’s still not working” moments turn into a five-minute check instead of a mystery.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b71ff7e1b169" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>