0
0
iOS Swiftmobile~15 mins

Push notifications (APNs + FCM) in iOS Swift - Deep Dive

Choose your learning style9 modes available
Overview - Push notifications (APNs + FCM)
What is it?
Push notifications are messages sent from a server to a mobile app to alert users even when the app is not open. On iOS devices, Apple Push Notification service (APNs) delivers these messages securely. Firebase Cloud Messaging (FCM) is a cross-platform service by Google that helps send notifications to iOS, Android, and web apps. Together, APNs and FCM enable apps to keep users informed and engaged in real time.
Why it matters
Without push notifications, apps would struggle to notify users about important updates, messages, or events unless the user opens the app. This reduces user engagement and can make apps less useful. Push notifications solve this by delivering timely alerts that bring users back to the app, improving user experience and retention.
Where it fits
Before learning push notifications, you should understand basic iOS app development and networking concepts. After mastering push notifications, you can explore advanced topics like notification customization, analytics, and integrating notifications with backend services.
Mental Model
Core Idea
Push notifications are like postcards sent from a server to your phone, delivered by a trusted postal service (APNs or FCM) that ensures they arrive even if the app is closed.
Think of it like...
Imagine you want to tell a friend something important, but they might not be home. You send a postcard through the postal service. The postal service guarantees delivery, and your friend reads it when they get home. APNs and FCM are like that postal service for your phone.
┌───────────────┐      ┌───────────────┐      ┌───────────────┐
│   App Server  │─────▶│ APNs / FCM    │─────▶│ User's Device │
└───────────────┘      └───────────────┘      └───────────────┘
       │                      │                      │
       │  Sends notification   │  Delivers message    │  Shows alert
       ▼                      ▼                      ▼
Build-Up - 7 Steps
1
FoundationWhat Are Push Notifications
🤔
Concept: Introduction to the basic idea of push notifications and their purpose.
Push notifications are short messages sent to your phone from an app's server. They can show alerts, badges, or sounds to get your attention. They work even if the app is not open, helping apps communicate important info instantly.
Result
You understand that push notifications are messages that apps use to talk to you anytime.
Understanding the basic purpose of push notifications helps you see why apps need a way to reach users outside the app.
2
FoundationRole of APNs in iOS
🤔
Concept: Learn what Apple Push Notification service (APNs) is and how it fits in iOS notifications.
APNs is Apple's secure system that delivers push notifications to iPhones and iPads. When your app wants to send a notification, it talks to APNs, which then sends it to the device. APNs handles delivery, security, and device management.
Result
You know APNs is the middleman that safely delivers notifications to iOS devices.
Knowing APNs is essential because it is the only way iOS devices receive push notifications.
3
IntermediateFirebase Cloud Messaging Basics
🤔
Concept: Understand how FCM works as a cross-platform notification service and its relation to APNs.
Firebase Cloud Messaging (FCM) is a service by Google that helps send notifications to many platforms, including iOS. For iOS, FCM uses APNs behind the scenes. Your app server sends messages to FCM, which forwards them to APNs, then to the device.
Result
You see FCM as a helpful tool that simplifies sending notifications to multiple platforms, including iOS via APNs.
Understanding FCM's role helps you build apps that work across devices without managing multiple notification services.
4
IntermediateRegistering for Notifications in iOS
🤔Before reading on: do you think the app can receive notifications without asking the user first? Commit to yes or no.
Concept: Learn how iOS apps ask permission and register to receive push notifications.
iOS apps must ask users for permission to show notifications. This is done by registering with the system using code like UNUserNotificationCenter.current().requestAuthorization. Once granted, the app registers with APNs to get a device token needed to receive notifications.
Result
Your app can now receive notifications because the user allowed it and the device token is ready.
Knowing the permission step is crucial because users control whether your app can notify them.
5
IntermediateHandling Device Tokens Securely
🤔Before reading on: do you think the device token is secret or public? Commit to your answer.
Concept: Understand what device tokens are and how to use them safely.
A device token is a unique ID that APNs gives your app to identify the device. Your app sends this token to your server, which uses it to target notifications. Tokens must be kept secure and updated because they can change.
Result
You can send notifications to the right device using the token, ensuring messages reach the user.
Understanding device tokens prevents common bugs where notifications fail because of wrong or outdated tokens.
6
AdvancedCustomizing Notifications with Payloads
🤔Before reading on: do you think notifications can only show text, or can they include images and buttons? Commit to your answer.
Concept: Learn how to send rich notifications with images, sounds, and actions using payloads.
Notifications carry a payload, a small data package describing what to show. You can include text, images, sounds, and buttons users can tap. This makes notifications more engaging and interactive. Payloads must follow APNs and FCM format rules.
Result
Your app shows rich notifications that attract user attention and allow quick actions.
Knowing how to customize payloads lets you create better user experiences and higher engagement.
7
ExpertManaging Notification Delivery and Failures
🤔Before reading on: do you think all notifications always arrive instantly and reliably? Commit to yes or no.
Concept: Explore how APNs and FCM handle delivery, retries, and what happens when devices are offline.
APNs and FCM queue notifications and try to deliver them when the device is online. If the device is offline, messages may be delayed or dropped based on priority and expiration. Understanding these rules helps you design notifications that arrive timely and avoid spamming users.
Result
You can build robust notification systems that handle failures gracefully and respect user experience.
Knowing delivery mechanics prevents surprises in production and helps maintain user trust.
Under the Hood
When an app registers for notifications, iOS contacts APNs to get a device token. The app sends this token to its server. When the server wants to notify the user, it sends a message with the token to APNs (or FCM, which forwards to APNs). APNs then routes the message securely to the device. The device wakes the app or shows the notification based on the payload. APNs manages queues, retries, and device reachability.
Why designed this way?
Apple designed APNs as a centralized, secure service to protect user privacy and battery life. By controlling delivery, APNs prevents apps from abusing notifications. FCM was created by Google to simplify cross-platform messaging, abstracting platform differences and providing analytics and easy integration.
┌───────────────┐      ┌───────────────┐      ┌───────────────┐
│   App Server  │─────▶│  FCM Server   │─────▶│     APNs      │─────▶ Device
└───────────────┘      └───────────────┘      └───────────────┘
       ▲                      ▲                      ▲
       │                      │                      │
  Sends token             Forwards             Routes message
  and payload            notification          securely to device
Myth Busters - 4 Common Misconceptions
Quick: Do you think push notifications always arrive instantly? Commit to yes or no.
Common Belief:Push notifications are instant and guaranteed to arrive immediately.
Tap to reveal reality
Reality:Notifications can be delayed or dropped if the device is offline or if the message expires before delivery.
Why it matters:Assuming instant delivery can cause developers to rely on notifications for critical real-time data, leading to poor user experience if messages are delayed.
Quick: Do you think the device token is permanent and never changes? Commit to yes or no.
Common Belief:Once you get a device token, it stays the same forever.
Tap to reveal reality
Reality:Device tokens can change, especially after app reinstall or system updates, so apps must handle token updates properly.
Why it matters:Using outdated tokens causes notifications to fail silently, frustrating users and developers.
Quick: Do you think Firebase Cloud Messaging replaces APNs on iOS? Commit to yes or no.
Common Belief:FCM completely replaces APNs for iOS notifications.
Tap to reveal reality
Reality:FCM uses APNs under the hood for iOS devices; it does not replace it but acts as a middleman.
Why it matters:Misunderstanding this can lead to misconfigurations and failed notifications on iOS.
Quick: Do you think users must always allow notifications for apps to work? Commit to yes or no.
Common Belief:Apps can send notifications without user permission.
Tap to reveal reality
Reality:iOS requires explicit user permission before sending notifications; apps cannot bypass this.
Why it matters:Ignoring permission requirements can cause apps to crash or fail silently when trying to register for notifications.
Expert Zone
1
APNs uses a persistent, secure HTTP/2 connection to deliver notifications efficiently and reduce battery use.
2
FCM supports topic messaging and device groups, enabling scalable notification targeting beyond single devices.
3
Payload size limits and priority flags affect how and when notifications are delivered, requiring careful tuning for best UX.
When NOT to use
Push notifications are not suitable for large data transfers or guaranteed real-time communication; use in-app messaging or real-time sockets instead. Also, avoid overusing notifications to prevent user annoyance and opt for silent notifications or background fetch when possible.
Production Patterns
In production, apps use token refresh handling, analytics to track notification engagement, and segmented messaging via FCM topics or APNs device tokens. They also implement fallback mechanisms and user preferences to control notification frequency and content.
Connections
Event-driven Architecture
Push notifications are a form of event-driven communication between servers and clients.
Understanding event-driven systems helps grasp how notifications trigger app behavior asynchronously and efficiently.
Email Delivery Systems
Both push notifications and email use servers to deliver messages reliably to users.
Comparing push notifications to email delivery reveals shared challenges like retries, queuing, and user preferences.
Postal Mail System
Push notifications resemble postal mail where messages are sent via trusted intermediaries to recipients.
Knowing how postal systems handle delivery and failures helps understand notification delivery guarantees and limitations.
Common Pitfalls
#1Not requesting user permission before sending notifications.
Wrong approach:UNUserNotificationCenter.current().getNotificationSettings { settings in if settings.authorizationStatus == .authorized { // Send notification } } // Missing requestAuthorization call
Correct approach:UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in if granted { // Register for notifications } }
Root cause:Developers forget that iOS requires explicit user permission before notifications can be sent.
#2Hardcoding device tokens and not updating them.
Wrong approach:let deviceToken = "fixed_token_string" // Using this token forever without refresh
Correct approach:func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { let tokenString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined() // Send tokenString to server }
Root cause:Misunderstanding that device tokens can change and must be updated dynamically.
#3Sending large payloads exceeding APNs size limits.
Wrong approach:{ "aps": { "alert": "Very long message..." }, "data": { "image": "base64encodedstring..." } } // Payload too large
Correct approach:{ "aps": { "alert": "Short message" }, "mutable-content": 1, "media-url": "https://example.com/image.jpg" } // Use media URL for rich content
Root cause:Ignoring APNs payload size limits and how to include rich content properly.
Key Takeaways
Push notifications let apps send messages to users even when apps are closed, improving engagement.
APNs is Apple's secure delivery system for iOS notifications; FCM is a cross-platform service that uses APNs for iOS.
Apps must request user permission and handle device tokens carefully to receive notifications reliably.
Notification payloads can be customized with text, images, and actions to create rich user experiences.
Understanding delivery mechanics and limitations helps build robust, user-friendly notification systems.