Firebase Cloud Messaging iOS:无后台推送通知 [英] Firebase Cloud Messaging iOS: No background push notification

查看:30
本文介绍了Firebase Cloud Messaging iOS:无后台推送通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用较新的 Firebase 云消息传递和方法 swizzling,当我的应用程序处于 前台 时,我能够成功地在我的应用程序委托中的 didReceiveRemoteNotification 方法中接收有效负载.但是,我没有收到任何类型的有效负载,并且 didReceiveRemoteNotification 在我的应用程序处于 背景 时不会被调用,尽管消息已成功发送的 api 响应(见下文)
这是我发送到 FCM api 以触发推送通知的请求 https://fcm.googleapis.com/fcm/send

Using the newer Firebase cloud messaging with method swizzling i am successfully able to receive a payload in the didReceiveRemoteNotification method in my app delegate when my app is foregrounded. However i do not get any sort of payload and didReceiveRemoteNotification does not get called when my app is backgrounded, despite the api response that the message is successfully sent (see below)
Here is the request that i send to the FCM api to trigger a push notification https://fcm.googleapis.com/fcm/send

{
"to": "{valid-registration-token}",
"priority":"high", //others suggested setting priority to high would fix, but did not
  "notification":{
      "body":"Body3",
      "title":"test"  
 } 
}


来自 FCM 的回应


with response from FCM

{
      "multicast_id": 6616533575211076304,
      "success": 1,
      "failure": 0,
      "canonical_ids": 0,
      "results": [
        {
          "message_id": "0:1468906545447775%a4aa0efda4aa0efd"
        }
      ]
    }

这是我的 appDelegate 代码

Here is my appDelegate code

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        Fabric.with([Crashlytics.self])
        FIRApp.configure()

        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) {
        // Let FCM know about the message for analytics etc.
        FIRMessaging.messaging().appDidReceiveMessage(userInfo)

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

        // handle your message

//        let localNotification = UILocalNotification()
//        localNotification.fireDate = NSDate()
//        let notification = userInfo["notification"]!
//        localNotification.alertBody = notification["body"] as? String
//        localNotification.alertTitle = notification["title"] as? String
//        localNotification.timeZone = NSTimeZone()
//        application.scheduleLocalNotification(localNotification)

    }

    func tokenRefreshNotification(notification: NSNotification) {
        let refreshedToken = FIRInstanceID.instanceID().token()!
        print("InstanceID token: \(refreshedToken)")
        LoginVC.registerForPushNotifications()
        connectToFcm()
    }


    //foreground messages
    func applicationDidBecomeActive(application: UIApplication) {
        connectToFcm()
    }

    // [START disconnect_from_fcm]
    func applicationDidEnterBackground(application: UIApplication) {
        FIRMessaging.messaging().disconnect()
        print("Disconnected from FCM.")
    }


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

}

我在我的应用程序的稍后流程中调用此代码以请求权限

I call this code at a later flow in my app to ask for permissions

static func registerForPushNotifications() {
    let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
            UIApplication.sharedApplication().registerUserNotificationSettings(settings)
            UIApplication.sharedApplication().registerForRemoteNotifications()
}

因为我能够在应用程序处于前台时收到通知,所以我认为这会消除所有关于我的 apns 证书未上传或注册令牌不正确的担忧.如果不是这种情况,请发表评论,我会再次进入那个兔子洞.我可能忽略了一些简单的事情,但是如何在应用程序处于后台时显示通知?谢谢

Since i am able to receive notifications while app is foregrounded i assume this would allay all concerns that my apns certificates are not uploaded or that the registration token is incorrect. If that is not the case, please comment and i'll go down that rabbit hole again. There's probably something simple that i am overlooking, but how can i get the notifications to appear while the app is backgrounded? Thanks

推荐答案

显然,(尽管使用方法 swizzling 应该自动执行)您仍然必须在 Firebase 实例上设置 APNS 令牌.因此,这意味着您还必须实现 didRegisterForRemoteNOtificationsWithDeviceToken 方法类似

Apparently, (despite using method swizzling that should be doing it automatically) you must still set the APNS token on the Firebase Instance. Consequently this means you must also implement the didRegisterForRemoteNOtificationsWithDeviceToken method with something like

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {


        // set firebase apns token
        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Unknown)
}

作为补充说明.使用 "priority":"high" 对测试很有用,因为它会立即发送通知.

As an added note. Using "priority":"high" was useful for testing as it sent the notification right away.

这篇关于Firebase Cloud Messaging iOS:无后台推送通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆