【问题标题】:unable to receive the push notification in foreground using FCM无法使用 FCM 在前台接收推送通知
【发布时间】:2017-12-09 21:36:24
【问题描述】:

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

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 swift firebase push-notification firebase-cloud-messaging


    【解决方案1】:
    1. 在你的 AppDelegate 中添加这个函数:

      func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
          completionHandler([.alert, .sound, .badge])
      }
      
    2. 将 UNUserNotificationCenterDelegate 协议添加到您的 AppDelegate 类,如下所示:

      class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { 
      
    3. 在 didFinishLaunchingWithOptions 函数中添加以下行:

      UNUserNotificationCenter.current().delegate = self
      

    【讨论】:

      【解决方案2】:

      从 iOS 10 开始,您可以使用以下功能显示 Apple 的默认通知横幅。 通知行为将取决于您在 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:

      您需要自己处理。就像如果您想在收到通知时显示横幅,而应用程序处于前台状态。您需要自己执行此操作。您必须设计自定义通知横幅以在应用内显示。

      希望对您有所帮助。

      【讨论】:

      • 我仍然无法接收前台通知,请告诉我如何设计自定义通知横幅。
      • 你在 iOS 10 或更低版本中测试这个?
      • 要创建自定义通知横幅,请查看此存储库 github.com/Daltron/NotificationBanner 以及 github 上的更多可用信息。
      • ohh.. 那一定是因为我在 IOS 9.3.5 上测试应用
      • 是的,在iOS 10以下,您必须在应用处于前台状态时使用自定义横幅来显示横幅。
      猜你喜欢
      • 1970-01-01
      • 2018-04-22
      • 2017-06-13
      • 2020-06-21
      • 1970-01-01
      • 2019-05-15
      • 1970-01-01
      • 1970-01-01
      • 2019-06-28
      相关资源
      最近更新 更多