简体   繁体   English

Firebase通知未在iOS应用程序中显示警报或横幅和徽章应用程序图标

[英]Firebase notification not showing alert or banner and badge app icon in iOS Application

  • I have designed an iOS app with push notification enable in it. 我设计了一个启用了推送通知的iOS应用。 Notification throw through FCM (just for checking), it will only print in console in foreground mode. 通过FCM发出通知(仅用于检查),它将仅在前台模式的控制台中打印。 But when app is in background mode it will not show any notification. 但是当应用程序处于后台模式时,它将不会显示任何通知。
  • I am registered in Apple Developer Program account. 我已在Apple Developer Program帐户中注册。
  • In this account I have created an app id with push notification enable and certificate (for production). 在此帐户中,我创建了一个具有推送通知启用和证书(用于生产)的应用程序ID。
  • Created .p12 and .pem file. 创建了.p12和.pem文件。
  • Also created Provisioning Profile (AdHoc) 还创建了配置文件(AdHoc)
  • Implemented code as given in Firebase for notification in xcode 8 for iOS 10+. 在Firebase中提供的已实现代码,用于iOS 10+的xcode 8中的通知。
  • Properly generated device token. 正确生成的设备令牌。 Still not able to get notification. 仍然无法收到通知。 Please help.. 请帮忙..

Appdelegate code: 代理代码:

import UIKit 
import UserNotifications
import Firebase
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    let gcmMessageIDKey = "gcm.message_id"

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

        // Register for remote notifications. This shows a permission dialog on first run, to
        // show the dialog at a more appropriate time move this registration accordingly.
        // [START register_for_notifications]
        if #available(iOS 10.0, *) {
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self

            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })

            // For iOS 10 data message (sent via FCM)
            FIRMessaging.messaging().remoteMessageDelegate = self

        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()

        // [END register_for_notifications]
        FIRApp.configure()

        // [START add_token_refresh_observer]
        // Add observer for InstanceID token refresh callback.
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(self.tokenRefreshNotification),
                                               name: .firInstanceIDTokenRefresh,
                                               object: nil)
        // [END add_token_refresh_observer]
        return true
    }

    /* [START receive_message]*/
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        // If you are receiving a notification message while your app is in the background,
        // this callback will not be fired till the user taps on the notification launching the application.
        // TODO: Handle data of notification
        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        // Print full message.
        print(userInfo)
    }

    /*[END receive_message]
     [START refresh_token] */
    func tokenRefreshNotification(_ notification: Notification) {
        if let refreshedToken = FIRInstanceID.instanceID().token() {
            print("InstanceID token: \(refreshedToken)")
        }

        // Connect to FCM since connection may have failed when attempted before having a token.
        connectToFcm()
    }

    /* [END refresh_token]
     / [START connect_to_fcm]*/
    func connectToFcm() {
        // Won't connect since there is no token
        guard FIRInstanceID.instanceID().token() != nil else {
            return;
        }

        // Disconnect previous FCM connection if it exists.
        FIRMessaging.messaging().disconnect()

        FIRMessaging.messaging().connect { (error) in
            if error != nil {
                print("Unable to connect with FCM. \(error)")
            } else {
                print("Connected to FCM.")
            }
        }
    }

    /* This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
     If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
     the InstanceID token.*/
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("APNs token retrieved: \(deviceToken)")

        // With swizzling disabled you must set the APNs token here.
        // FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox)

        if let refreshedToken = FIRInstanceID.instanceID().token() {
            print("InstanceID token 1: \(refreshedToken)")
        }
    }


    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        // If you are receiving a notification message while your app is in the background,
        // this callback will not be fired till the user taps on the notification launching the application.
        // TODO: Handle data of notification
        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID in didReceiveRemoteNotification: \(messageID)")
        }

        // Print full message.
        print("didReceiveRemoteNotification: \(userInfo)")

        completionHandler(UIBackgroundFetchResult.newData)
    }

    // [END connect_to_fcm]
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Unable to register for remote notifications: \(error.localizedDescription)")
    }



    /* [START connect_on_active]*/
    func applicationDidBecomeActive(_ application: UIApplication) {
        connectToFcm()
    }


     /*[END connect_on_active]
     [START disconnect_from_fcm]*/
    func applicationDidEnterBackground(_ application: UIApplication) {
        //FIRMessaging.messaging().disconnect()
       // print("Disconnected from FCM.")

        connectToFcm()
          print("connected to FCM in Background.")
    }
    // [END disconnect_from_fcm]
}

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
        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID in UNUserNotificationCenterDelegate: \(messageID)")
        }

        // Print full message.
        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
        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID in userNotificationCenter: \(messageID)")
        }

        // Print full message.
        print(userInfo)

        completionHandler()
    }
}

extension AppDelegate : FIRMessagingDelegate {

    // Receive data message on iOS 10 devices while app is in the foreground.
    func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
        print("applicationReceivedRemoteMessage: \(remoteMessage.appData)")
    }

}

To receive and show notifications in background mode just make sure you have enable "Push Notifications" in "Capabilities" section. 要在后台模式下接收和显示通知,只需确保已在“功能”部分中启用了“推送通知”。

And to display notifications in foreground mode add alert, badge & sound parameters to your completion block in willPresent method. 要以前台模式显示通知,请在willPresent方法中将警报,徽章和声音参数添加到您的完成块中。

completionHandler([.alert, .badge, .sound]) completeHandler([。alert,.badge,.sound])

 // 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
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID in UNUserNotificationCenterDelegate: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    // Change this to your preferred presentation option
    completionHandler([.alert, .badge, .sound])
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 应用程序图标 iOS 上未显示徽章 - Badge not showing on application icon iOS 通知到达时未显示应用程序图标徽章 - App icon badge not showing when notification arrives 在 ios 中接收通知时禁用应用程序徽章图标 - Disable application badge icon on receiving notification in ios 查找启动应用程序的事件:横幅通知,警报通知或图标点击? - Find event launching the application: banner notification, alert notification or icon tap? Flutter:主屏幕上 iOS 应用程序图标上的通知徽章计数器未显示(使用 FCM) - Flutter: The notification badge counter on the iOS app icon on the home screen is not showing up (using FCM) iOS推送通知徽章编号超过图标未显示 - iOS push notification badge number over icon is not showing 推送通知-应用徽章图标 - Push Notification - App Badge Icon IOS 应用程序中未收到 Firebase 推送通知徽章计数 - Firebase push notification badge count is not being received in IOS app 在不运行应用程序或不发送推送通知的情况下为iOS应用程序添加徽章? - Badge iOS application without running the app or sending a push notification? iOS推送通知-检查应用程序在后台时横幅是否显示 - iOS Push Notification - check if the banner is showing when app is in background
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM