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

本文介绍了推送通知已交付,但 didReceiveRemoteNotification 从未被称为 Swift的处理方法,对大家解决问题具有一定的参考价值

问题描述

我已通过 FCM 在我的两个相关应用中成功实现推送通知,并尝试实现一些逻辑以在收到通知时增加徽章编号.

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.

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

I realized that didReceiveRemoteNotificationdelegate method is not called at all as I don't get any prints out of it, but I do get prints from willPresent notificationand didReceive response. So setting UIApplication.shared.applicationIconBadgeNumber in didFinishLaunchingWithOptionshas no effect, but setting in it didReceive responsedoes.

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

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 didReceiveRemoteNotificationmethod and notifications are still delivered.

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

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 方法:

AppDelegate methods:

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

推荐答案

我终于找到了解决方案.警报需要"content_available": true 在从 App2 到 App1 的帖子发送功能的警报定义中设置,否则会传递通知但不调用didReceiveRemoteNotification",您不能使用userInfo"'.希望这对其他人有所帮助,因为我没有找到有关此问题的太多信息.如果您使用 Postman 或类似工具设置通知,请在此处查看 didReceiveRemoteNotification 函数不使用 FCM 通知服务器调用,因为这是我在这个问题上找到的唯一帖子并解决了我的问题.感谢@Ranjani 尝试帮助我.

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'. 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. Thanks to @Ranjani for trying helping me.

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",
            ]
                ]

这篇关于推送通知已交付,但 didReceiveRemoteNotification 从未被称为 Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2

admin_action_{$_REQUEST[‘action’]}

do_action( "admin_action_{$_REQUEST[‘action’]}" )动作钩子::在发送“Action”请求变量时激发。Action Hook: Fires when an ‘action’ request variable is sent.目录锚点:#说明#源码说明(Description)钩子名称的动态部分$_REQUEST['action']引用从GET或POST请求派生的操作。源码(Source)更新版本源码位置使用被使用2.6.0 wp-admin/admin.php:...

日期:2020-09-02 17:44:16 浏览:1170

admin_footer-{$GLOBALS[‘hook_suffix’]}

do_action( "admin_footer-{$GLOBALS[‘hook_suffix’]}", string $hook_suffix )操作挂钩:在默认页脚脚本之后打印脚本或数据。Action Hook: Print scripts or data after the default footer scripts.目录锚点:#说明#参数#源码说明(Description)钩子名的动态部分,$GLOBALS['hook_suffix']引用当前页的全局钩子后缀。参数(Parameters)参数类...

日期:2020-09-02 17:44:20 浏览:1071

customize_save_{$this->id_data[‘base’]}

do_action( "customize_save_{$this->id_data[‘base’]}", WP_Customize_Setting $this )动作钩子::在调用WP_Customize_Setting::save()方法时激发。Action Hook: Fires when the WP_Customize_Setting::save() method is called.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分,$this->id_data...

日期:2020-08-15 15:47:24 浏览:808

customize_value_{$this->id_data[‘base’]}

apply_filters( "customize_value_{$this->id_data[‘base’]}", mixed $default )过滤器::过滤未作为主题模式或选项处理的自定义设置值。Filter Hook: Filter a Customize setting value not handled as a theme_mod or option.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分,$this->id_date['base'],指的是设置...

日期:2020-08-15 15:47:24 浏览:900

get_comment_author_url

过滤钩子:过滤评论作者的URL。Filter Hook: Filters the comment author’s URL.目录锚点:#源码源码(Source)更新版本源码位置使用被使用 wp-includes/comment-template.php:32610...

日期:2020-08-10 23:06:14 浏览:930

network_admin_edit_{$_GET[‘action’]}

do_action( "network_admin_edit_{$_GET[‘action’]}" )操作挂钩:启动请求的处理程序操作。Action Hook: Fires the requested handler action.目录锚点:#说明#源码说明(Description)钩子名称的动态部分$u GET['action']引用请求的操作的名称。源码(Source)更新版本源码位置使用被使用3.1.0 wp-admin/network/edit.php:3600...

日期:2020-08-02 09:56:09 浏览:877

network_sites_updated_message_{$_GET[‘updated’]}

apply_filters( "network_sites_updated_message_{$_GET[‘updated’]}", string $msg )筛选器挂钩:在网络管理中筛选特定的非默认站点更新消息。Filter Hook: Filters a specific, non-default site-updated message in the Network admin.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分$_GET['updated']引用了非默认的...

日期:2020-08-02 09:56:03 浏览:864

pre_wp_is_site_initialized

过滤器::过滤在访问数据库之前是否初始化站点的检查。Filter Hook: Filters the check for whether a site is initialized before the database is accessed.目录锚点:#源码源码(Source)更新版本源码位置使用被使用 wp-includes/ms-site.php:93910...

日期:2020-07-29 10:15:38 浏览:834

WordPress 的SEO 教学:如何在网站中加入关键字(Meta Keywords)与Meta 描述(Meta Description)?

你想在WordPress 中添加关键字和meta 描述吗?关键字和meta 描述使你能够提高网站的SEO。在本文中,我们将向你展示如何在WordPress 中正确添加关键字和meta 描述。为什么要在WordPress 中添加关键字和Meta 描述?关键字和说明让搜寻引擎更了解您的帖子和页面的内容。关键词是人们寻找您发布的内容时,可能会搜索的重要词语或片语。而Meta Description则是对你的页面和文章的简要描述。如果你想要了解更多关于中继标签的资讯,可以参考Google的说明。Meta 关键字和描...

日期:2020-10-03 21:18:25 浏览:1730

谷歌的SEO是什么

SEO (Search Engine Optimization)中文是搜寻引擎最佳化,意思近于「关键字自然排序」、「网站排名优化」。简言之,SEO是以搜索引擎(如Google、Bing)为曝光媒体的行销手法。例如搜寻「wordpress教学」,会看到本站的「WordPress教学:12个课程…」排行Google第一:关键字:wordpress教学、wordpress课程…若搜寻「网站架设」,则会看到另一个网页排名第1:关键字:网站架设、架站…以上两个网页,每月从搜寻引擎导入自然流量,达2万4千:每月「有机搜...

日期:2020-10-30 17:23:57 浏览:1308