Swift・iOS

Swiftを中心に学んだことを記録に残すブログです。技術に関係ない記事もたまに書いています。

【Firebase Cloud Messaging】受信したメッセージを処理する

 

はじめに

【Firebase Cloud Messaging】導入の手順 - Swift・iOSの続きです。今回は受信したプッシュ通知のメッセージを処理する方法について記事にします。

 

開発環境

  • macOS Catalina 10.15.7
  • Xcode 12.2
  • Swift 5.3.1
  • CocoaPods 1.10.0
  • FirebaseMessaging 7.3.0

 

本題

以下のように、AppDelegate.swiftにメソッドを追加する。

AppDelegate.swift

// 通知が到着した時の挙動
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([[.banner, .sound]])
}
    
// 通知を選択した時の挙動
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    print(userInfo)
    completionHandler()
}

  

実際に受信したメッセージの中身は以下のような構造になっている。

※値は実際のものから変更しています。

[
    AnyHashable("google.c.a.udt"): 0,
    AnyHashable("gcm.message_id"): 0,
    AnyHashable("google.c.sender.id"): 0,
    AnyHashable("google.c.a.e"): 0, 
AnyHashable("gcm.n.e"): 0, AnyHashable("google.c.a.ts"): 0, AnyHashable("google.c.a.c_id"): 0, AnyHashable("aps"): { alert = { body = ""; title = ""; }; "mutable-content" = 0; } ]

そのため、例えば通知のタイトルと本文を取得したい場合は、userNotificationCenter(_:didReceive:withCompletionHandler:)メソッドの中身を以下のように変更する。

// 通知を選択した時の挙動
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    let aps = userInfo["aps"] as? [AnyHashable: Any]
    let alert = aps?["alert"] as? [AnyHashable: Any]
    let title = alert?["title"]
    let body = alert?["body"]
    print(title ?? "")
    print(body ?? "")
        
    completionHandler()
}

 

おわりに

今回は簡単なメッセージの処理について記事にしてみましたが、通知周りはまだまだできることがあるので、試したらまた記事にしたいと思います。

 

参考