0
0
iOS Swiftmobile~7 mins

Push notifications (APNs + FCM) in iOS Swift

Choose your learning style9 modes available
Introduction

Push notifications let apps send messages to users even when the app is closed. They help keep users informed and engaged.

To alert users about new messages or updates in a chat app.
To remind users about upcoming events or appointments.
To send promotional offers or news from a shopping app.
To notify users about important system alerts or security warnings.
Syntax
iOS Swift
import UserNotifications

// Request permission
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
  if granted {
    DispatchQueue.main.async {
      UIApplication.shared.registerForRemoteNotifications()
    }
  }
}

// AppDelegate methods
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  // Send deviceToken to your server or Firebase
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
  print("Failed to register: \(error)")
}

APNs (Apple Push Notification service) is Apple's system to send notifications to iOS devices.

FCM (Firebase Cloud Messaging) is a service by Google that helps send notifications to multiple platforms including iOS.

Examples
This asks the user if the app can send alerts and play sounds.
iOS Swift
// Request permission for notifications
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { granted, error in
  print("Permission granted: \(granted)")
}
This tells iOS to get a device token for push notifications.
iOS Swift
// Register for remote notifications
UIApplication.shared.registerForRemoteNotifications()
This converts the device token to a string to send to your server or Firebase.
iOS Swift
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  let tokenString = deviceToken.map { String(format: "%02hhx", $0) }.joined()
  print("Device Token: \(tokenString)")
}
Sample App

This example shows how to ask permission, register for push notifications, and print the device token. It also handles showing notifications when the app is open.

iOS Swift
import UIKit
import UserNotifications

@main
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    UNUserNotificationCenter.current().delegate = self
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
      if granted {
        DispatchQueue.main.async {
          UIApplication.shared.registerForRemoteNotifications()
        }
      } else {
        print("Notification permission denied")
      }
    }
    return true
  }

  func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let tokenParts = deviceToken.map { String(format: "%02hhx", $0) }
    let token = tokenParts.joined()
    print("Device Token: \(token)")
  }

  func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Failed to register: \(error.localizedDescription)")
  }

  // Handle notification when app is in foreground
  func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([.banner, .sound])
  }
}
OutputSuccess
Important Notes

Always test push notifications on a real device; the simulator does not support them.

Make sure your app's bundle ID matches the one in your Apple Developer account for push notifications.

FCM requires setting up Firebase in your project and uploading APNs certificates or keys.

Summary

Push notifications keep users updated even when the app is closed.

Use APNs to get device tokens and send notifications on iOS.

FCM helps manage and send notifications across platforms including iOS.