Complete the code to request user permission for push notifications in Swift.
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, [1]]) { granted, error in if granted { print("Permission granted") } }
The .badge option allows the app to show badge counts on the app icon, which is part of push notification permissions.
Complete the code to register for remote notifications after permission is granted.
DispatchQueue.main.async {
UIApplication.shared.[1]()
}The method registerForRemoteNotifications() tells iOS to start receiving push notifications from APNs.
Fix the error in the delegate method to receive the device token for APNs.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken [1]: Data) { let tokenParts = [2].map { data in String(format: "%02.2hhx", data) } let token = tokenParts.joined() print("Device Token: \(token)") }
The parameter name must be deviceToken to match the delegate method signature exactly.
Fill both blanks to create a dictionary payload for Firebase Cloud Messaging (FCM) with a notification title and body.
let message: [String: Any] = [
"notification": [
"title": [1],
"body": [2]
]
]The notification dictionary requires string values for title and body. Here, "Hello" is the title and "Welcome to the app!" is the body.
Fill all three blanks to handle receiving a push notification in the app delegate and print its content.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.[1].request.content.[2]
print("Received notification with info: \(userInfo)")
completionHandler([3])
}The notification parameter has a request property, which has content. The content contains userInfo dictionary with the notification data. The completion handler is called with presentation options like [.alert, .sound] to show the notification while the app is in foreground.