使用 FCM 时无法在前台接收推送通知

6

我一直在尝试在我的应用程序中获取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]
}
2个回答

21

iOS 14以后,.alert已经被弃用,你可以使用.banner代替:

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

从iOS 10开始,您可以使用以下函数来显示苹果默认的通知横幅。通知行为将取决于您在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之前:

您需要自己处理这个问题。例如,如果您想在应用程序处于前台状态时收到通知并显示横幅,则需要自己处理。您必须设计自定义通知横幅以在应用程序内部显示。

希望对您有所帮助。


1
我仍然无法在前台接收通知,请问您能告诉我如何设计自定义通知横幅吗? - kunal kushwaha
你是在 iOS 10 或更低版本中测试吗? - Surjeet Singh
要创建自定义通知横幅,请查看此代码库https://github.com/Daltron/NotificationBanner,GitHub上还有许多其他可用的资源。 - Surjeet Singh
是的,在低于 iOS 10 的版本中,您必须使用自定义横幅来在应用程序处于前台状态时显示横幅。 - Surjeet Singh
:) @kunalkushwaha - Surjeet Singh
显示剩余4条评论

3
  1. Add this func in your AppDelegate:

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .sound, .badge])
    }
    
  2. Add UNUserNotificationCenterDelegate protocol to your AppDelegate class like this:

    class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { 
    
  3. Add below line in didFinishLaunchingWithOptions func:

    UNUserNotificationCenter.current().delegate = self
    

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