当前位置: 首页 > 知识库问答 >
问题:

FCM后台通知在iOS中不工作

姜玉泽
2023-03-14
{  
   "data":{  
      "title":"mytitle",
      "body":"mybody",
      "url":"myurl"
   },
   "notification":{  
      "title":"mytitle",
      "body":"mybody"
   },
   "to":"/topics/topic"
}

您可以看到,我的JSON中有两个块:一个通知块(在后台接收通知),一个数据块(在前台接收通知)。

我不明白为什么没有收到后台通知。我的怀疑是关于块的顺序(如果我把“数据”块放在“通知”块之前会有问题吗?)。

编辑:有关问题的更多信息。

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
{
    var window: UIWindow?


    // Application started
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool
    {
        let pushNotificationSettings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
        application.registerUserNotificationSettings(pushNotificationSettings)
        application.registerForRemoteNotifications()

        FIRApp.configure()

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "tokenRefreshNotification:", name: kFIRInstanceIDTokenRefreshNotification, object: nil)

        return true
    }




    // Handle refresh notification token
    func tokenRefreshNotification(notification: NSNotification) {
        let refreshedToken = FIRInstanceID.instanceID().token()
        print("InstanceID token: \(refreshedToken)")

        // Connect to FCM since connection may have failed when attempted before having a token.
        if (refreshedToken != nil)
        {
            connectToFcm()

            FIRMessaging.messaging().subscribeToTopic("/topics/topic")
        }

    }


    // Connect to FCM
    func connectToFcm() {
        FIRMessaging.messaging().connectWithCompletion { (error) in
            if (error != nil) {
                print("Unable to connect with FCM. \(error)")
            } else {
                print("Connected to FCM.")
            }
        }
    }


    // Handle notification when the application is in foreground
    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (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

            // Print message ID.
            print("Message ID: \(userInfo["gcm.message_id"])")

            // Print full message.
            print("%@", userInfo)
    }


    // Application will enter in background
    func applicationWillResignActive(application: UIApplication)
    {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }



    // Application entered in background
    func applicationDidEnterBackground(application: UIApplication)
    {
        FIRMessaging.messaging().disconnect()
        print("Disconnected from FCM.")
    }



    // Application will enter in foreground
    func applicationWillEnterForeground(application: UIApplication)
    {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }



    // Application entered in foreground
    func applicationDidBecomeActive(application: UIApplication)
    {
        connectToFcm()

        application.applicationIconBadgeNumber = 0;
    }



    // Application will terminate
    func applicationWillTerminate(application: UIApplication)
    {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}
 - FIRMessaging.messaging().appDidReceiveMessage(userInfo)  in didReceiveRemoteNotification callback
 - FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Sandbox) in didRegisterForRemoteNotificationsWithDeviceToken callback

编辑2:

当应用程序在后台时,不会收到通知,但当我打开应用程序时,会立即收到相同的通知(方法didReceiveRemoteNotification被激发)。

共有1个答案

南宫保臣
2023-03-14

假设您已正确设置了所有内容,那么将消息的prioritynormal设置为high应该会使它立即出现。这要归功于iOS捆绑通知和处理通知的方式。您可以在这里了解FCM通知的优先级。请注意,除非有充分的理由,否则不应该在生产中真正使用high,因为它会造成电池损失。

以下是苹果文档中的参考

通知的优先级。指定下列值之一:

 类似资料:
  • 问题内容: 我在iOS上的FCM通知有问题。 我收到成功通知时,我的应用程序是在前台(回调中被激发),但是当应用程序在后台(我看不出在iOS中的通知栏的任何东西)我没有收到通知。 因此,我认为问题在于FCM发送的消息格式。我的服务器发送到FCM的json格式如下: 如您所见,我的json中有两个块:一个通知块(用于在后台接收通知)和一个数据块(用于在前台接收通知)。 我不明白为什么没有收到后台通知

  • 当应用程序关闭时,我无法使通知工作。 我从FCM/GCM(python服务器)发送此消息: 所以curl是这样的: curl-头"授权:key=MYKEY"-头"内容类型:应用/json"https://fcm.googleapis.com/fcm/send-d'{"registration_ids":["APA91bEDB9dVf-..."],"collapse_key":空,"content_

  • 我尝试了以下各种组合: 在ap有效载荷中传递了一个空警报 一个空的声音通过ap有效载荷 content_available:真 内容可用: 1 优先级设置为高。我的目标功能在后台模式中启用了后台抓取和远程通知。 这是我的有效载荷的样子: 我一打开应用程序,通知就会进来,但不是在后台。 看起来是这样的: [AnyHasable("body"): NTCIP示例单元:现在显示WALNUT TREE(T

  • 我需要帮助。Firebase通知在后台不工作。这是我的代码:

  • 当用户未连接到xmpp时,我正在使用FCM通知进行聊天。 FCM中有两种通知模式1。通知消息2。数据消息 如果我的应用程序最近被清除,我将不会使用数据消息作为通知消息 这种方法适用于除奥利奥以外的所有版本。 对于Oreo,我只有在应用程序未连接到xmpp且处于前台时才会收到通知。我的onMessageReception方法正在被调用。 但当该应用程序仅为奥利奥而被删除或从最近的应用程序中删除时,情

  • 问题内容: 我需要处理推送通知,这是通过较低版本的ios完成的,但是在ios 11中,从未收到任何推送通知。我使用Firebase Cloud Messaging。请任何人有解决方案,然后请分享。 问题答案: func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UI