ios - 推送通知已发送但 didReceiveRemoteNotification 从未被称为 Swift

标签 ios swift firebase push-notification firebase-cloud-messaging

我已经通过 FCM 在我的两个相关应用程序中成功实现了推送通知,同时尝试实现一些逻辑以在收到通知时增加角标(Badge)编号。

我意识到 didReceiveRemoteNotificationdelegate 方法根本没有被调用,因为我没有从中得到任何打印,但我确实从 willPresent notificationdidReceive 响应。所以在 didFinishLaunchingWithOptions 中设置 UIApplication.shared.applicationIconBadgeNumber 没有效果,但是在里面设置 didReceive response 有效果。

按照文档 didReceiveRemoteNotification 应该被调用,但是当通知到达时我从来没有打印出来。

我尝试注释掉整个 didReceiveRemoteNotification 方法,通知仍然会发送。

为什么会这样?我想我真的不明白谁在这个设置中处理消息传递。你能帮我澄清一下吗?

AppDelegate 方法:

didFinishLaunchingWithOptions:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        window?.tintColor = UIColor.blue
        // Use Firebase library to configure APIs
        FirebaseApp.configure()
        Messaging.messaging().delegate = self
        Crashlytics().debugMode = true
        Fabric.with([Crashlytics.self])
        // setting up notification delegate
        if #available(iOS 10.0, *) {
            //iOS 10.0 and greater
            UNUserNotificationCenter.current().delegate = self
            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            //Solicit permission from the user to receive notifications
            UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { granted, error in
                DispatchQueue.main.async {
                    if granted {
                        print("didFinishLaunchingWithOptions iOS 10: Successfully registered for APNs")
                        UIApplication.shared.registerForRemoteNotifications()
//                        UIApplication.shared.applicationIconBadgeNumber = 1
                        AppDelegate.badgeCountNumber = 0
                        UIApplication.shared.applicationIconBadgeNumber = 0
                    } else {
                        //Do stuff if unsuccessful...
                        print("didFinishLaunchingWithOptions iOO 10: Error in registering for APNs: \(String(describing: error))")
                    }
                }
            })
        } else {
            //iOS 9
            let type: UIUserNotificationType = [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound]
            let setting = UIUserNotificationSettings(types: type, categories: nil)
            UIApplication.shared.registerUserNotificationSettings(setting)
            UIApplication.shared.registerForRemoteNotifications()
//            UIApplication.shared.applicationIconBadgeNumber = 1
            UIApplication.shared.applicationIconBadgeNumber = 0
            print("didFinishLaunchingWithOptions iOS 9: Successfully registered for APNs")
        }
        // setting up remote control values
        let _ = RCValues.sharedInstance
        GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
        Crashlytics().debugMode = true
        Fabric.with([Crashlytics.self])
        //        // TODO: Move this to where you establish a user session
        //        self.logUser()
        var error: NSError?
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        } catch let error1 as NSError{
            error = error1
            print("could not set session. err:\(error!.localizedDescription)")
        }
        do {
            try AVAudioSession.sharedInstance().setActive(true)
        } catch let error1 as NSError{
            error = error1
            print("could not active session. err:\(error!.localizedDescription)")
        }
        // goggle only
        GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
//        GIDSignIn.sharedInstance().delegate = self
        // Facebook SDK
        return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
//        return true
    }

didReceiveRemoteNotification:

 // foreground
        func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
            print("didReceiveRemoteNotification: Received new push Notification")
            // 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)
            AppDelegate.badgeCountNumber += userInfo["badge"] as! Int
            print("AppDelegate.badgeCountNumber is : \(String(describing: AppDelegate.badgeCountNumber))")
//            UIApplication.shared.applicationIconBadgeNumber = AppDelegate.badgeCountNumber
            UIApplication.shared.applicationIconBadgeNumber =  10//AppDelegate.badgeCountNumber
            // Print full message.
            print("didReceiveRemoteNotification: Push notificationMessage is: \(userInfo)")
        }




        // background
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print("didReceiveRemoteNotification with handler : Received new push Notification while in background")
        // 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)
        if let messageID = userInfo[ userDetails.fcmToken] { // working for looged in
            print("didReceiveRemoteNotification: Message ID: \(messageID)")
        }

        // Print full message.
        print("didReceiveRemoteNotification: Push notificationMessage is: \(userInfo)")
        AppDelegate.badgeCountNumber += userInfo["badge"] as! Int
        print("AppDelegate.badgeCountNumber is : \(String(describing: AppDelegate.badgeCountNumber))")
        UIApplication.shared.applicationIconBadgeNumber +=  userInfo["badge"] as! Int
        completionHandler(UIBackgroundFetchResult.newData)
    }

最佳答案

我终于找到了解决方案。 Alert needs"content_available": true 要在从 App2 到 App1 的帖子发送功能的警报定义中设置,否则通知已发送但未调用 'didReceiveRemoteNotification`,您不能使用 'userInfo '.希望这会对其他人有所帮助,因为我还没有找到有关此问题的太多信息。如果您使用 Postman 或类似工具设置通知,请在此处查看 didReceiveRemoteNotification function doesn't called with FCM notification server因为那是我在这个问题上找到并解决了我的唯一帖子。 感谢@Ranjani 试图帮助我。

let postParams: [String : Any] = [
                "to": receiverToken,
                "notification": [
                    "badge" : 1,
                    "body": body,
                    "title": title,
                    "subtitle": subtitle,
                    "sound" : true, // or specify audio name to play
                    "content_available": true, // this will call didReceiveRemoteNotification in receiving app, else won't work
                    "priority": "high"
                ],
                "data" : [
                    "data": "ciao",
            ]
                ]

关于ios - 推送通知已发送但 didReceiveRemoteNotification 从未被称为 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56376255/

相关文章:

ios - 从 Here Api 计算 ETA 后未收到回调

firebase - 在 flutter 中使用 withConverter 获取 Firestore 文档引用字段的数据

ios - 如何处理后台 url session 丢失的互联网连接?

ios - 改进通过JSON将服务器数据库镜像到客户端数据库的过程?

ios - Singleton类中的Init方法(Objective-C)

swift - GCD 未按 block 顺序执行

android - Firebase 数据库依赖项使应用程序崩溃

ios - Objective C - 按值传递和按引用传递

swift - 在 Storyboard中创建继承属性的导出

ios - FrameLayout IOS替代方案