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

标签 ios swift firebase push-notification firebase-cloud-messaging

我一直在尝试在我的应用程序中获取 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 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 开始,您可以使用以下函数显示 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() 为空。因为当应用程序处于前台状态时,通知横幅不会显示。

早期的 iO​​S 10:

你需要自己处理。就像你想在收到通知时显示横幅,而应用程序处于前台状态。你需要自己做这件事。您必须设计要在应用内显示的自定义通知横幅。

希望对你有帮助。

关于ios - 无法使用 FCM 在前台接收推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44939407/

相关文章:

ios - 如何获取用户所在楼层?

ios - 使用谓词从数组中获取无序数据

swift - 检查字符串是否包含文本字段中的文本

firebase - 通过 REST API 优先推送到 Firebase

firebase - FieldValue.arrayRemove() 根据属性值从对象数组中删除一个对象

ios - 从 NSDate 创建绝对时间

ios - 用户说 iOS 应用程序崩溃没有任何进一步的解释

ios - APNS?还是轮询?哪个更靠谱?

swift - 如何调整显示在警报 Controller 上的图像的大小?

java - 如何在位置感知应用中多次使用 Google Places API?