Firebase通知(仅数据)在前台未接收到

7
大家好,我看到一些人在使用Firebase和iOS通知时遇到了问题,但似乎没有人遇到同样的问题。
目前,我只讨论应用程序处于前台状态时的情况:
如果应用程序收到具有类似以下参数的通知,则会收到通知: ```notification```.
let notificationsParameters:[String:AnyObject] = [
        "to": "iphoneID",
        "content-available":true,
        "priority":"high",
// "notification" : [
//                "body" : "great match!",
//                "title" : "Portugal vs. Denmark",
//                "icon" : "myicon"
//            ],
        "data" : [
            "Nick" : "Mario",
            "Room" : "PortugalVSDenmark"
        ]
    ]

但是,一旦我移除了通知部分,应用程序就无法接收到任何内容,即使保持在前台,而根据我的观察,每个人都应该接收通知。

我将优先级设置为高,即使关闭/后台也能接收和content-available,我读到这应该解决我的问题,但实际情况并非如此。

以下是涉及的代码:

APP DELEGATE

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.



        GMSServices.provideAPIKey(Constants.GoogleMaps.APIKey)
        FIRApp.configure()


        /* NOTFICATIONS */

        let notificationsType:UIUserNotificationType = [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound]
        let notificationSettings = UIUserNotificationSettings(forTypes: notificationsType, categories: nil)
        application.registerForRemoteNotifications()
        application.registerUserNotificationSettings(notificationSettings)

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


        return true
    }

通知(在应用程序委托中)

我的理解是,这将接收到通知的数据。

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

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

        connectToFCM()
    }

    func connectToFCM() {
        FIRMessaging.messaging().connectWithCompletion { (error) in
            if error != nil {
                print("GMS ERROR: \(error)")
            }
            else {
                print("Connected to GMS")
            }
        }
    }

调用Firebase通知

func sendNotification() {

        let notificationsParameters:[String:AnyObject] = [
            "to": "iphoneID",
            "content-available":true,
            "priority":"high",
            //            "notification" : [
            //                "body" : "great match!",
            //                "title" : "Portugal vs. Denmark",
            //                "icon" : "myicon"
            //            ],
            "data" : [
                "Nick" : "Mario",
                "Room" : "PortugalVSDenmark"
            ]
        ]


        let URL = NSURL(string: "https://fcm.googleapis.com/fcm/send")!
        let URLRequest = NSMutableURLRequest(URL: URL)

        URLRequest.HTTPMethod = "POST"

        URLRequest.setValue("key=\(Constants.Firebase.NotificationsKey)", forHTTPHeaderField: "Authorization")
        URLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")

        let encoding = Alamofire.ParameterEncoding.JSON

        let encoded = encoding.encode(URLRequest, parameters: (notificationsParameters)).0
        Alamofire.request(encoded)
    }

如果您需要任何进一步的信息,请告诉我!


你解决了这个问题吗? - Suhas Arvind Patil
2个回答

5
你的方向是正确的,但在content_available参数中需要使用下划线而不是连字符。如果你想使用FCM发送数据(静默)通知,就不需要使用notification对象。
例如,在你的FCM请求体中:
{
    "to": "iPhoneID",
    "content_available": true,
    "priority": "high",
    "data": {
        "nick": "mario",
        "room": "PortugalVSDenmark"
    }
}

这应该是被接受的答案。content_available起了很大的作用。在此链接中,第三段缺少此信息:https://firebase.google.com/docs/cloud-messaging/ios/receive#handle-data-messages-in-foregrounded-apps - Gazihan Alankus

3
对于像我一样遇到同样问题的人,一个解决方案是设置通知参数如下所示:
let notificationsParameters:[String:AnyObject] = [
            "to": "iphoneID",
            "content-available":true,
            "priority":"high",
           "notification" : [
               "sound" : " "
           ],
            "data" : [
                "Nick" : "Mario",
                "Room" : "PortugalVSDenmark"
            ]
        ]

当应用程序被杀死时,您将无法收到通知,但在前台和后台时,您仍可以接收数据通知,祝好运!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接