1
2

More than 3 years have passed since last update.

iOSでパラメータ付きのPUSH通知を受け取る

Last updated at Posted at 2020-11-10

この記事の前提として、既にPUSH通知は届く状態とします。

PUSH通知の実装に関する参考資料:
iOS で Firebase Cloud Messaging クライアント アプリを設定する

初期設定では、アプリが起動している場合はPUSH通知のバナーは表示されません。
次の didReceiveRemoteNotification に値が届きます。


class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        // 省略...

        Messaging.messaging().delegate = self

        // 省略...
}

extension AppDelegate: MessagingDelegate {

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print(userInfo)
    }

}

ただ UNUserNotificationCenter を繋いだ場合は上記の didReceiveRemoteNotification は呼ばれなくなり、下記のfuncが呼ばれるようになりました。
また completionHandler に返す値により、アプリが全面にあってもPUSH通知のバナーが表示されるようになります。

アプリ起動時も起動していないときも、didReceiveはタップした場合に呼ばれました。
PUSH通知をタップする処理があるケースでは didReceiveRemoteNotification は利用しないかもしれないですね。

extension AppDelegate : UNUserNotificationCenterDelegate {

    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo

        print(userInfo)

        if #available(iOS 14.0, *) {
            completionHandler([[.banner, .list, .sound]])
        } else {
            completionHandler([[.alert, .sound]])
        }

        // NOTE: push通知を表示したくない場合はこちら
        // completionHandler([])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo

        // 起動してない時に楽にuserInfoを確認するためにアラートで表示
        if let rootViewController = (UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.window?.rootViewController {
            let alertController = UIAlertController(title: "userInfo", message: userInfo.description, preferredStyle: .alert)
            let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
            alertController.addAction(okAction)
            rootViewController.present(alertController, animated: true, completion: nil)
        }

        completionHandler()
    }

}

参考文献

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2