🍎 Swift & iOS Intermediate

What is push notifications and APNs in iOS?

Answer

Push notifications deliver information to users even when the app isn't active. Apple Push Notification service (APNs) is the gateway between your server and Apple's infrastructure that routes notifications to devices. How it works: app registers for notifications → Apple issues a device token → app sends token to your server → server sends notification payload + device token to APNs → APNs delivers to device. Requesting permission (iOS 10+): import UserNotifications func requestPermission() { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in if granted { DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } } } }. AppDelegate — receiving device token: func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined() sendTokenToServer(token) } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("Failed: \(error)") }. Handling notification in foreground: extension AppDelegate: UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler handler: @escaping (UNNotificationPresentationOptions) -> Void) { handler([.banner, .badge, .sound]) } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo handleDeepLink(userInfo) completionHandler() } }. Local notifications: scheduled without a server. Rich notifications: images, actions, custom UI.