簡體   English   中英

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

[英]unable to receive the push notification in foreground using FCM

我一直在嘗試在我的應用程序中獲取 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 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:

你需要自己處理這個。 就像您想在收到通知時顯示橫幅一樣,而應用程序處於前台狀態。 你需要自己做這件事。 您必須設計您的自定義通知橫幅以在應用程序中顯示。

希望對你有幫助。

  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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM