简体   繁体   English

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

[英]Push Notifications are delivered but didReceiveRemoteNotification is never called Swift

I have successfully implemented push notifications in my two related apps via FCM and while trying to implement some logic to increment badge number on receiving the notification.我已经通过 FCM 在我的两个相关应用程序中成功实施了推送通知,同时尝试实施一些逻辑以在收到通知时增加徽章编号。

I realized that didReceiveRemoteNotification delegate method is not called at all as I don't get any prints out of it, but I do get prints from willPresent notification and didReceive response .我意识到didReceiveRemoteNotification委托方法根本没有被调用,因为我没有从中得到任何打印,但我确实从willPresent notificationdidReceive response得到了打印。 So setting UIApplication.shared.applicationIconBadgeNumber in didFinishLaunchingWithOptions has no effect, but setting in it didReceive response does.所以在didFinishLaunchingWithOptions设置UIApplication.shared.applicationIconBadgeNumber没有效果,但在didReceive response中设置。

Following the documentation didReceiveRemoteNotification should be called but I never get prints out of it when a notification arrives.按照文档didReceiveRemoteNotification应该被调用,但是当通知到达时我永远不会打印出来。

I tried commenting out the whole didReceiveRemoteNotification method and notifications are still delivered.我尝试注释掉整个didReceiveRemoteNotification方法,通知仍然发送。

Why is it so?为什么会这样? I guess I didn't really understand who's handling messaging in this set up.我想我真的不明白在这个设置中谁在处理消息。 Can you please help me clarifying it?你能帮我澄清一下吗?

AppDelegate methods: AppDelegate 方法:

didFinishLaunchingWithOptions : 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 : 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)
    }

I finally found the solution.我终于找到了解决方案。 Alert needs "content_available": true to be set in the alert definition from the post sending funtion from App2 to App1 or else notifications get delivered but 'didReceiveRemoteNotification` is not called and you can't use 'userInfo'.警报需要"content_available": true才能在从 App2 到 App1 的帖子发送功能的警报定义中设置,否则通知会被传递但未调用“didReceiveRemoteNotification”,并且您不能使用“userInfo”。 Hope this will help others as I haven't found much info about this problem.希望这会对其他人有所帮助,因为我还没有找到有关此问题的太多信息。 If you're setting the notification with Postman or similars check here didReceiveRemoteNotification function doesn't called with FCM notification server as that's the only post I found on this problem and solved mine.如果您使用 Postman 或类似工具设置通知,请在此处检查didReceiveRemoteNotification 函数不会使用 FCM 通知服务器调用,因为这是我在此问题上找到并解决了我的问题的唯一帖子。 Thanks to @Ranjani for trying helping me.感谢@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",
            ]
                ]

For Node.js (send to topic example)对于 Node.js(发送到主题示例)

var admin = require("firebase-admin");

var serviceAccount = require("path/to/serviceAccountKey.json");

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "<your database URL>"
});

var topic = "topicA";

var payload = {
    notification: {
        title: "title",
        body: "body",
        sound: "default"
    },
    data: {
        a: "dataA",
        b: "dataB"
    }
};

var options = {
    content_available: true,
    priority: "high",
    timeToLive: 1
};

// Send a message to devices subscribed to the provided topic.
admin.messaging().sendToTopic(topic, payload, options)
    .then((response) => {
        // Response is a message ID string.
        console.log('Successfully sent message:', response);
    })
    .catch((error) => {
        console.log('Error sending message:', error);
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 CloudKit推送通知didReceiveRemoteNotification从未调用过 - CloudKit Push Notifications didReceiveRemoteNotification never called iOS推送通知-didReceiveRemoteNotification:fetchCompletionHandler:从不在前台调用 - iOS push notifications - didReceiveRemoteNotification:fetchCompletionHandler: never called in foreground DidReceiveRemoteNotification 不在后台调用 - Xamarin iOS - 推送通知 - DidReceiveRemoteNotification is not called in background - Xamarin iOS - Push Notifications didReceiveRemoteNotification不称为swift - didReceiveRemoteNotification not called swift Swift &amp; Push Notification:application(_:didReceiveRemoteNotification:fetchCompletionHandler:) 没有被调用 - Swift & Push Notification : application(_:didReceiveRemoteNotification:fetchCompletionHandler:) does not get called didReceiveRemoteNotification 未调用 Swift - didReceiveRemoteNotification not called Swift Swift didReceiveRemoteNotification 未调用 - Swift didReceiveRemoteNotification not called 推送通知未提供quickblox - Push Notifications not delivered quickblox 每次推送通知都不会调用didReceiveRemoteNotification - didReceiveRemoteNotification is not called for every push notification 解析并快速处理:didReceiveRemoteNotification未接收到带有“ aps”:{“ content-available”:1}的推送通知 - Parse and Swift: Push notifications with “aps”: {“content-available”: 1} not being received by didReceiveRemoteNotification
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM