AppDelegateを使用しないSwiftUIリモートプッシュ通知(Firebase Cloud Messaging)

レジー

SwiftUI 2.0でリモートプッシュ通知を実装しようとしていますが、AppDelegateがありません。経由で提供できること@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegateは知っていますが、お勧めできないことを学びました。

Firebase Cloud Messagingを介して通知をトリガーしようとしましたが、テスト通知を受け取りません。通知を許可するためのポップアップが表示されました。

エラーなどは発生しません。実際には何も起こりません。

私は何かが足りないのですか?

テスト:

ここに画像の説明を入力してください

Firebase registration token: Optional("fwRsIKd7aUZeoLmmW5b4Zo:APA91bHrVvArS-mLZMEkdtzTxhRUuMWVgHNKXdLethAvR3Fa3h_RmAcdOz_jJzp1kDsEEtcvbnAFUn9eh9-cUSCTy9jBibbFoR2xngWdzWCvci1_iLQJtHtCjxk-C02CkVUDl7FX8esp")

これが私のコードです:

import SwiftUI
import Firebase
import OSLog

@main
struct Le_fretApp: App {
    @StateObject var sessionStore = SessionStore()
    @StateObject var locationManagerService = LocationManagerService()
    @StateObject var userViewModel = UserViewModel()
    
    var notificationsService = NotificationsService()
    
    
    
    init() {
        UIApplication.shared.delegate = NotificationsService.Shared
        FirebaseConfiguration.shared.setLoggerLevel(.min)
        
        notificationsService.register()
        
        FirebaseApp.configure()
        
        notificationsService.setDelegate()
    }
    
    var body: some Scene {
        WindowGroup {
            TabViewContainerView()
                .environmentObject(sessionStore)
                .environmentObject(userViewModel)
                .environmentObject(locationManagerService)
                .onAppear {
                    sessionStore.listen()
                    userViewModel.listen()
                }
        }
    }
}

サービス:

import Foundation
import UserNotifications
import OSLog
import UIKit

import Firebase


class NotificationsService: NSObject, UNUserNotificationCenterDelegate {
    static let Shared = NotificationsService()
    let gcmMessageIDKey = "gcmMessageIDKey"
    
    func register() {
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self
        
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: {_, _ in })
        
        DispatchQueue.main.async {
          UIApplication.shared.registerForRemoteNotifications()
        }
    }
    

      // Receive displayed notifications for iOS 10 devices.
      func userNotificationCenter(_ center: UNUserNotificationCenter,
                                  willPresent notification: UNNotification,
        withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo

        // With swizzling disabled you must let Messaging know about the message, for Analytics
        // Messaging.messaging().appDidReceiveMessage(userInfo)

        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey] {
          print("Message ID: \(messageID)")
        }

        // Print full message.
        print(userInfo)

        // Change this to your preferred presentation option
        completionHandler([[.alert, .sound]])
      }

      func userNotificationCenter(_ center: UNUserNotificationCenter,
                                  didReceive response: UNNotificationResponse,
                                  withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey] {
          print("Message ID: \(messageID)")
        }

        // With swizzling disabled you must let Messaging know about the message, for Analytics
        // Messaging.messaging().appDidReceiveMessage(userInfo)

        // Print full message.
        print(userInfo)

        completionHandler()
      }
}

extension NotificationsService: UIApplicationDelegate {
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
      // If you are receiving a notification message while your app is in the background,
      // this callback will not be fired till the user taps on the notification launching the application.
      // TODO: Handle data of notification

      // With swizzling disabled you must let Messaging know about the message, for Analytics
      // Messaging.messaging().appDidReceiveMessage(userInfo)

      // Print message ID.
      if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
      }

      // Print full message.
      print(userInfo)
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
      // If you are receiving a notification message while your app is in the background,
      // this callback will not be fired till the user taps on the notification launching the application.
      // TODO: Handle data of notification

      // With swizzling disabled you must let Messaging know about the message, for Analytics
      // Messaging.messaging().appDidReceiveMessage(userInfo)

      // Print message ID.
      if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
      }

      // Print full message.
      print(userInfo)

      completionHandler(UIBackgroundFetchResult.newData)
    }
}

extension NotificationsService: MessagingDelegate {
    func setDelegate() {
        Messaging.messaging().delegate = self
    }
    
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
      print("Firebase registration token: \(String(describing: fcmToken))")

      let dataDict:[String: String] = ["token": fcmToken ?? ""]
      NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
      // TODO: If necessary send token to application server.
      // Note: This callback is fired at each app startup and whenever a new token is generated.
    }
}
ダビデ

を作成しましたApp Delegateローカルおよびリモート通知で機能します。

私が持っているPushNotificationManagerリモートプッシュを行うことを。Firebaseにデータを送信するときはいつでも(Firestoreを使用AppDelegate.fcmTokenしています)、をユーザーのfcmTokenプロパティに渡します(すべてのユーザーがモデルに1つ持っています)token: user.fcmToken

class AppDelegate: NSObject, UIApplicationDelegate {
    
    private var gcmMessageIDKey = "gcm_message_idKey"
    static var fcmToken = String()
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        
        FirebaseApp.configure()
        Messaging.messaging().delegate = self
        UNUserNotificationCenter.current().delegate = self
        registerForPushNotifications()
        
        return true
    }
    
    func registerForPushNotifications() {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { [weak self] granted, _ in
            print("Permission granted: \(granted)")
            guard granted else { return }
            self?.getNotificationSettings()
        }
    }
    
    func getNotificationSettings() {
        UNUserNotificationCenter.current().getNotificationSettings { settings in
            print("Notification settings: \(settings)")
            guard settings.authorizationStatus == .authorized else { return }
            DispatchQueue.main.async {
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    }
    
    func application(
        _ application: UIApplication,
        didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
       
        AppDelegate.fcmToken = deviceToken.hexString
    }
    
    func application(
        _ application: UIApplication,
        didFailToRegisterForRemoteNotificationsWithError error: Error
    ) {
        print("Failed to register: \(error.localizedDescription)")
    }
    
    func application(
        _ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
        fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
       
        print(userInfo)
        completionHandler(.newData)
    }
}

拡張機能

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
    
    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        willPresent notification: UNNotification,
        withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        
        let userInfo = notification.request.content.userInfo
        print("Will Present User Info: \(userInfo)")
        
        completionHandler([[.banner, .sound]])
    }
    
    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        didReceive response: UNNotificationResponse,
        withCompletionHandler completionHandler: @escaping () -> Void) {
        
        let userInfo = response.notification.request.content.userInfo
        
        if response.actionIdentifier == "accept" {
            print("Did Receive User Info: \(userInfo)")
            
            completionHandler()
        }
    }
}

extension AppDelegate: MessagingDelegate {
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
        let dataDict: [String: String] = [AppDelegate.fcmToken: fcmToken ?? ""]
        NotificationCenter.default.post(name: NSNotification.Name("FCMToken"), object: nil, userInfo: dataDict)

        // Note: This callback is fired at each app startup and whenever a new token is generated.
        AppDelegate.fcmToken = fcmToken!
    }
}

extension Data {
    var hexString: String {
        let hexString = map { String(format: "%02.2hhx", $0) }.joined()
        return hexString
    }
}

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

XMPPサーバーとプッシュ通知用のGoogle Cloud Messaging(または新しいFirebase Cloud Messaging)を使用したAndroid向けチャットアプリ

分類Dev

Firebase Cloud Messaging AppDelegateエラー

分類Dev

Notification from Firebase cloud messaging are received but they are not shown in the cloud messaging reports

分類Dev

Firebase Cloud Messaging Statistics API

分類Dev

Firebase Cloud Messaging 通知キー名

分類Dev

Firebase Cloud Messagingを使用して毎日のプッシュ通知を作成する

分類Dev

Firebase Cloud Messaging - Error calling firebase.messaging()

分類Dev

Firebase Cloud Messaging - Managing Registration Tokens

分類Dev

Firebase Cloud Messaging notification not received on iOS

分類Dev

Firebase Cloud MessagingはVOIPプッシュキットサービスをサポートしていますか?

分類Dev

Delphi Android Firebase Cloud Messaging:通知の受信時にアプリケーションがクラッシュする

分類Dev

Firebase Cloud Messagingはプッシュ通知を作成しませんが情報を取得します

分類Dev

Firebase Cloud Messagingで送信されたプッシュの5%を受信していないAndroidデバイス

分類Dev

新しいFirebase Cloud Messagingシステムの通知アイコン

分類Dev

Firebase Cloud Messagingを使用してJSONプッシュ通知本文で太字のテキストを送信することは可能ですか?

分類Dev

Firebase Cloud Messaging SystemUIが停止しました

分類Dev

JSON を Firebase Cloud Messaging に送信する

分類Dev

Firebase Cloud Messaging - Target to single device not visible in Firebase console

分類Dev

Firebase Cloud Messaging: Device Group sending support in Firebase Admin SDK

分類Dev

Does Firebase Cloud Messaging support VOIP pushkit services?

分類Dev

Firebase Cloud Messagingは無料ですか?

分類Dev

Firebase Cloud Messagingは無料ですか?

分類Dev

How to auto increment iOS notification badge with Firebase Cloud Messaging?

分類Dev

How to migrate Azure Notification hub to Firebase Cloud Messaging?

分類Dev

Firebase Cloud Messaging認証は必要ですか?

分類Dev

Firebase send http cloud messaging from android app

分類Dev

Is it possible to use Firebase Cloud Messaging API to list all push notifications?

分類Dev

Firebase Cloud Messaging in flutter function works but didn't receive notification

分類Dev

新しい Google Play アプリと Firebase Cloud Messaging

Related 関連記事

  1. 1

    XMPPサーバーとプッシュ通知用のGoogle Cloud Messaging(または新しいFirebase Cloud Messaging)を使用したAndroid向けチャットアプリ

  2. 2

    Firebase Cloud Messaging AppDelegateエラー

  3. 3

    Notification from Firebase cloud messaging are received but they are not shown in the cloud messaging reports

  4. 4

    Firebase Cloud Messaging Statistics API

  5. 5

    Firebase Cloud Messaging 通知キー名

  6. 6

    Firebase Cloud Messagingを使用して毎日のプッシュ通知を作成する

  7. 7

    Firebase Cloud Messaging - Error calling firebase.messaging()

  8. 8

    Firebase Cloud Messaging - Managing Registration Tokens

  9. 9

    Firebase Cloud Messaging notification not received on iOS

  10. 10

    Firebase Cloud MessagingはVOIPプッシュキットサービスをサポートしていますか?

  11. 11

    Delphi Android Firebase Cloud Messaging:通知の受信時にアプリケーションがクラッシュする

  12. 12

    Firebase Cloud Messagingはプッシュ通知を作成しませんが情報を取得します

  13. 13

    Firebase Cloud Messagingで送信されたプッシュの5%を受信していないAndroidデバイス

  14. 14

    新しいFirebase Cloud Messagingシステムの通知アイコン

  15. 15

    Firebase Cloud Messagingを使用してJSONプッシュ通知本文で太字のテキストを送信することは可能ですか?

  16. 16

    Firebase Cloud Messaging SystemUIが停止しました

  17. 17

    JSON を Firebase Cloud Messaging に送信する

  18. 18

    Firebase Cloud Messaging - Target to single device not visible in Firebase console

  19. 19

    Firebase Cloud Messaging: Device Group sending support in Firebase Admin SDK

  20. 20

    Does Firebase Cloud Messaging support VOIP pushkit services?

  21. 21

    Firebase Cloud Messagingは無料ですか?

  22. 22

    Firebase Cloud Messagingは無料ですか?

  23. 23

    How to auto increment iOS notification badge with Firebase Cloud Messaging?

  24. 24

    How to migrate Azure Notification hub to Firebase Cloud Messaging?

  25. 25

    Firebase Cloud Messaging認証は必要ですか?

  26. 26

    Firebase send http cloud messaging from android app

  27. 27

    Is it possible to use Firebase Cloud Messaging API to list all push notifications?

  28. 28

    Firebase Cloud Messaging in flutter function works but didn't receive notification

  29. 29

    新しい Google Play アプリと Firebase Cloud Messaging

ホットタグ

アーカイブ