この記事の前提として、既に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()
}
}