How to register for alert push notification in iOS

Issue #452

Use UserNotifications framework

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import FirebaseMessaging
import UserNotifications

final class PushHandler: NSObject {
private let center = UNUserNotificationCenter.current()
private let options: UNAuthorizationOptions = [.alert]

func setup() {
Messaging.messaging().delegate = self
}

func register() {
center.requestAuthorization(options: options, completionHandler: { granted, error in
print(granted, error)
self.getSettings()
})
}

func getSettings() {
center.getNotificationSettings(completionHandler: { settings in
guard
case let .authorized = settings.authorizationStatus,
case let .enabled = settings.alertSetting,
settings.alertStyle != .none
else {
return
}

// TODO
})
}

func handle(userInfo: [AnyHashable: Any]) {

}
}

extension PushHandler: MessagingDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print(fcmToken)
}

func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print(remoteMessage)
}
}
1
2
3
4
5
6
7
8
9
10
11
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(
_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
completionHandler(.noData)

Deps.pushHandler.handle(userInfo: userInfo)
}
}

A test message from Firebase looks like

1
2
3
4
5
6
[AnyHashable("google.c.a.e"): 1, AnyHashable("google.c.a.ts"): 1570701857, AnyHashable("aps"): {
alert = {
body = Test;
title = Test;
};
}, AnyHashable("google.c.a.udt"): 0, AnyHashable("google.c.a.c_l"): Test, AnyHashable("gcm.message_id"): 1570701857965182, AnyHashable("google.c.a.c_id"): 1257698497812622975, AnyHashable("gcm.n.e"): 1]

Comments