Member-only story

Push Notification

  1. What are push notifications, and how do they work in iOS?

Answer: Push notifications are messages sent from a server to an iOS device, even when the app is not running. They are used to inform users of new data or events.

How to work

2. How do you register an iOS app for push notifications in Swift?

Answer: Use this method: requestAuthorization(options:)

import UIKit
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Request permission to show notifications
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
if granted {
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
}
}
return true
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Convert token to string
let tokenParts = deviceToken.map { data in…

--

--

Responses (1)