Firebase Messenger发送通知,但iOS设备未收到任何通知 [英] Firebase messenger sends a notification but iOS device doesn't receive anything

查看:185
本文介绍了Firebase Messenger发送通知,但iOS设备未收到任何通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取从Firebase云Messenger发送到单个设备的通知.我已经安装了firebase,当我运行该程序时,控制台会打印出fcm令牌,我试图将其用于向该设备发送消息(我使用的是真实的iPhone).消息发送正常,但我的iPhone上什么也没有出现.我在应用程序委托中实现了以下代码:

  func应用程序(_应用程序:UIApplication,didFinishLaunchingWithOptions launchOptions:[UIApplicationLaunchOptionsKey:任何]?)->布尔{UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)如果#available(iOS 10.0,*){//对于iOS 10显示通知(通过APNS发送)UNUserNotificationCenter.current().delegate =自我UNUserNotificationCenter.current().requestAuthorization(options:[.badge,.sound,.alert]){(授予,错误)在如果授予{//self.registerCategory()}}//对于iOS 10数据消息(通过FCM发送)Messaging.messaging().delegate =自我}别的{设置:UIUserNotificationSettings = UIUserNotificationSettings(类型:[.alert,.badge,.sound],类别:nil)application.registerUserNotificationSettings(设置)}application.registerForRemoteNotifications()//配置FirebaseFirebaseApp.configure()//为InstanceID令牌刷新回调添加观察者.NotificationCenter.default.addObserver(自身,选择器:#selector(self.tokenRefreshNotification),名称:NSNotification.Name.InstanceIDTokenRefresh,对象:nil)返回真}//在后台接收远程通知func应用程序(应用程序:UIApplication,didReceiveRemoteNotification userInfo:[NSObject:AnyObject],fetchCompletionHandlercompleteHandler:(UIBackgroundFetchResult)->无效){Messaging.messaging().appDidReceiveMessage(userInfo)}func应用程序(应用程序:UIApplication,didRegisterForRemoteNotificationsWithDeviceToken deviceToken:数据){Messaging.messaging().apnsToken = deviceToken}@objc func tokenRefreshNotification(通知:NSNotification){如果让refreshedToken = InstanceID.instanceID().token(){print("InstanceID令牌:\(refreshedToken)")}//连接到FCM,因为在获得令牌之前尝试连接可能会失败.connectToFcm()}func connectToFcm(){Messaging.messaging().should EstablishmentDirectChannel = true}func applicationDidBecomeActive(应用程序:UIApplication){connectToFcm()}func消息传递(_消息传递:Messaging,didReceiveRegistrationToken fcmToken:字符串){print("Firebase注册令牌:\(fcmToken)")//TODO:如有必要,将令牌发送到应用程序服务器.//注意:每次应用启动时以及每次生成新令牌时都会触发此回调.} 

然后实现消息处理方法在前景和背景中

  @available(iOS 10,*)扩展名AppDelegate:UNUserNotificationCenterDelegate {func userNotificationCenter(_中心:UNUserNotificationCenter,willPresent通知:UNNotification,withCompletionHandler completeHandler:@escaping(UNNotificationPresentationOptions)->空白) {让userInfo = notification.request.content.userInfoMessaging.messaging().appDidReceiveMessage(userInfo)如果让messageID = userInfo [gcmMessageIDKey] {}打印(userInfo)completeHandler([.alert,.badge,.sound])}func userNotificationCenter(_中心:UNUserNotificationCenter,didReceive响应:UNNotificationResponse,withCompletionHandler completeHandler:@escaping()->空白) {让userInfo = response.notification.request.content.userInfo如果让messageID = userInfo [gcmMessageIDKey] {print(消息ID:\(消息ID)")}completeHandler()}AppDelegate扩展名:MessagingDelegate {func消息传递(_消息传递:Messaging,didRefreshRegistrationToken fcmToken:字符串){print("Firebase注册令牌:(fcmToken)")}Messaging.messaging().应该将DirectChannel设置为true.func消息传递(_消息传递:Messaging,didReceive remoteMessage:MessagingRemoteMessage){print(接收到的数据消息:(remoteMessage.appData)")}} 

I'm trying to get a notification to send from firebase cloud messenger to single device. I've installed firebase and when I run the program the console prints out the fcm token which I attempt to use to send a message to that device (I'm using a real iPhone). The message sends fine but nothing ever appears on my iPhone. I implemented the code below in the App Delegate:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)



    if #available(iOS 10.0, *)
    {
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self
        UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert])          { (granted, error) in
            if granted
            {
                //self.registerCategory()
            }
        }
        // For iOS 10 data message (sent via FCM)
        Messaging.messaging().delegate = self
    }
    else
    {
        let settings: UIUserNotificationSettings =  UIUserNotificationSettings(types: [.alert,.badge,.sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }
    application.registerForRemoteNotifications()
    //Configuring Firebase
    FirebaseApp.configure()
    // Add observer for InstanceID token refresh callback.
    NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotification), name: NSNotification.Name.InstanceIDTokenRefresh, object: nil)


    return true
}


//Receive Remote Notification on Background
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void)
{
    Messaging.messaging().appDidReceiveMessage(userInfo)
}

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

    Messaging.messaging().apnsToken = deviceToken

}

@objc func tokenRefreshNotification(notification: NSNotification)
{
    if let refreshedToken = InstanceID.instanceID().token()
    {
        print("InstanceID token: \(refreshedToken)")
    }
    // Connect to FCM since connection may have failed when attempted before having a token.
    connectToFcm()
}

func connectToFcm()
{
    Messaging.messaging().shouldEstablishDirectChannel = true
}

func applicationDidBecomeActive(application: UIApplication)
{
    connectToFcm()
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
    print("Firebase registration token: \(fcmToken)")

    // TODO: If necessary send token to application server.
    // Note: This callback is fired at each app startup and whenever a new token is generated.
}

This is the response I get from the Firebase end

So it says no messages were sent, which I'm confused about because it is the token my device has just outputted as having.

How can I find out more about or solve this problem?

解决方案

before run messege from fcm console check .p12 file is uploaded

then implement the message handling methods in foreground and background

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo
    Messaging.messaging().appDidReceiveMessage(userInfo)
    if let messageID = userInfo[gcmMessageIDKey] {
    }

    print(userInfo)
    completionHandler([.alert, .badge, .sound])

   }

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }


    completionHandler()

}

extension AppDelegate : MessagingDelegate {
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
print("Firebase registration token: (fcmToken)")
}
Messaging.messaging().shouldEstablishDirectChannel to true.
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Received data message: (remoteMessage.appData)")
}
}

这篇关于Firebase Messenger发送通知,但iOS设备未收到任何通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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