无法使用FCM在前台接收推送通知 [英] unable to receive the push notification in foreground using FCM

查看:49
本文介绍了无法使用FCM在前台接收推送通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在我的应用中获取Firebase推送通知.我已经尝试了互联网上的所有内容,但找不到解决方案.我一直在后台收到通知,但是当App在前台时我无法收到通知.但是,当我在"didReceiveRemoteNotification"中打印userInfo时,会在控制台中收到消息任何帮助将不胜感激.

I have been trying to get firebase push-notification in my app. I have tried everything on the internet but couldn't find solution. I have been receiving notification in background, but when App is in foreground I am unable to get the notification. But when I print the userInfo in "didReceiveRemoteNotification" I get the message in console Any help would be appreciated.

import Firebase
import UserNotifications


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate{

var window: UIWindow?


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

    //FirebaseApp.configure()

    self.initializeFCM(application)
    let token = InstanceID.instanceID().token()
    debugPrint("GCM TOKEN = \(String(describing: token))")

    return true
}

 func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error)
{
    debugPrint("didFailToRegisterForRemoteNotificationsWithError: \(error)")
}

func application(received remoteMessage: MessagingRemoteMessage)
{
    debugPrint("remoteMessage:\(remoteMessage.appData)")
}

func initializeFCM(_ application: UIApplication)
{
    print("initializeFCM")

    if #available(iOS 10.0, *) // enable new way for notifications on iOS 10
    {
        let center = UNUserNotificationCenter.current()
        center.delegate = self
        center.requestAuthorization(options: [.badge, .alert , .sound]) { (accepted, error) in
            if !accepted
            {
                print("Notification access denied.")
            }
            else
            {
                print("Notification access accepted.")
                UIApplication.shared.registerForRemoteNotifications();
            }
        }
    }
    else
    {
        let type: UIUserNotificationType = [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound];
        let setting = UIUserNotificationSettings(types: type, categories: nil);
        UIApplication.shared.registerUserNotificationSettings(setting);
        UIApplication.shared.registerForRemoteNotifications();
    }

    FirebaseApp.configure()
    Messaging.messaging().delegate = self
    Messaging.messaging().shouldEstablishDirectChannel = true

}

// enable new way for notifications on iOS 10

func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings)
{
    debugPrint("didRegister notificationSettings")
    if (notificationSettings.types == .alert || notificationSettings.types == .badge || notificationSettings.types == .sound)
    {
        application.registerForRemoteNotifications()
    }
}


func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData)
{
    debugPrint("didRegisterForRemoteNotificationsWithDeviceToken: NSDATA")

    let token = String(format: "%@", deviceToken as CVarArg)
    debugPrint("*** deviceToken: \(token)")

    Messaging.messaging().apnsToken = deviceToken as Data
    debugPrint("Firebase Token:",InstanceID.instanceID().token() as Any)
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
    debugPrint("didRegisterForRemoteNotificationsWithDeviceToken: DATA")
    let token = String(format: "%@", deviceToken as CVarArg)
    debugPrint("*** deviceToken: \(token)")

    Messaging.messaging().apnsToken = deviceToken
    debugPrint("Firebase Token:",InstanceID.instanceID().token() as Any)
}
//-------------------------------------------------------------------------//

// [START receive_message]
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {

    Messaging.messaging().appDidReceiveMessage(userInfo)
    print(userInfo)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    Messaging.messaging().appDidReceiveMessage(userInfo)
    print(userInfo)

    completionHandler(UIBackgroundFetchResult.newData)
}
// [END receive_message]

}


// [START ios_10_message_handling]
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    Messaging.messaging().appDidReceiveMessage(userInfo)
    print(userInfo)

    // Change this to your preferred presentation option
    completionHandler([])
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    Messaging.messaging().appDidReceiveMessage(userInfo)
    print(userInfo)

    completionHandler()
 }
}
 // [END ios_10_message_handling]

 extension AppDelegate : MessagingDelegate {
// [START refresh_token]
 func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
    print("Firebase registration token: \(fcmToken)")
}

func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
    print("Received data message: \(remoteMessage.appData)")
}
// [END ios_10_data_message]
}

推荐答案

在iOS 10中,您可以使用以下功能显示Apple的默认通知横幅.通知行为将取决于您在completionHandler中返回的属性.

From iOS 10, You can display Apple's default notification banner using below function. Notification behaviour will depend on properties which you return within completionHandler.

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let content = notification.request.content
        // Process notification content
        print("\(content.userInfo)")
        completionHandler([.alert, .sound]) // Display notification Banner

    }

根据您问题的详细信息,您已经实现了上述功能,但具有空白的completionHandler().因此,当应用程序处于前台状态时,通知横幅不会显示.

早期的iOS 10:

您需要自己处理.就像是在应用程序处于前台状态时要在收到通知时显示横幅一样.您需要自己执行此操作.您必须设计自定义通知横幅才能在应用程序中显示.

You need to handle this by yourself. Like if you want to display banner when you received a notification, while app is in foreground state. You need to do this by yourself. You have to design your custom notification banner to display within app.

希望它对您有帮助.

这篇关于无法使用FCM在前台接收推送通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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