Swift ios 推送通知通知在应用程序打开时不起作用,但在应用程序关闭时起作用

Swift ios push notification notif not woking when app is open but its working when app is closed

如何处理推送通知,即使应用程序打开或关闭也会通知。我有 ff。下面的代码及其在应用程序关闭时发出通知,但在应用程序打开时不发出通知。我已经提供了我的源代码 below.Thank 你。极大地帮助 appreciated.How 处理推送通知,即使在应用程序打开或关闭时它也会通知。我有 ff。下面的代码及其在应用程序关闭时发出通知,但在应用程序打开时不发出通知。我已经提供了我的源代码 below.Thank 你。非常感谢帮助。

import UIKit
import CoreData
import Firebase
import FirebaseMessaging
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.


        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

        if UserDefaults.standard.bool(forKey: "isLoggedIn") {
            let  menuVC = storyBoard.instantiateViewController(withIdentifier: "MenuCollectionViewController") as! MenuCollectionViewController

            let nvc: UINavigationController = UINavigationController(rootViewController: menuVC)
            nvc.navigationBar.isHidden =  true

            self.window?.rootViewController = nvc
            self.window?.makeKeyAndVisible()

        } else {

           self.showLoginScreen()
        }

        FirebaseApp.configure()

        let notificationTypes : UIUserNotificationType = [UIUserNotificationType.alert , UIUserNotificationType.badge, UIUserNotificationType.sound]
        let notificationSettings = UIUserNotificationSettings(types: notificationTypes,categories : nil)

        application.registerForRemoteNotifications()
        application.registerUserNotificationSettings(notificationSettings)

        return true
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

//        print("MessageID: \(userInfo["gcm_message_id"])")
//        print(userInfo)

        if let message = userInfo["gcm_message_id"] {
            print("MessageID: \(message)")
        }
        print(userInfo)

    }

    func showLoginScreen()
    {

        UserDefaults.standard.set(false, forKey: "isLoggedIn")
        UserDefaults.standard.synchronize()


        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let loginViewController = storyboard.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController

        let nvc: UINavigationController = UINavigationController(rootViewController: loginViewController)
        nvc.navigationBar.isHidden = true
        self.window?.rootViewController = nvc
        self.window?.makeKeyAndVisible()

    }

    func applicationWillResignActive(_ application: UIApplication) {

    }

    func applicationDidEnterBackground(_ application: UIApplication) {

    }

    func applicationWillEnterForeground(_ application: UIApplication) {

    }

    func applicationDidBecomeActive(_ application: UIApplication) {

    }

    func applicationWillTerminate(_ application: UIApplication) {

    }


    lazy var persistentContainer: NSPersistentContainer = {

        let container = NSPersistentContainer(name: "FridgeBoard")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {

                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()


    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {

                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }



}

请使用此代码

       @UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,CLLocationManagerDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    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 })
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }
        application.registerForRemoteNotifications()
    }



   @available(iOS 10, *)

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

    // print(userInfo)
      completionHandler([.alert, .badge, .sound])
    // 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: \(messageID)")
    }
    switch response.actionIdentifier {
    case "action1":
        print("Action First Tapped")
    case "action2":
        print("Action Second Tapped")
    default:
        break
    }

    // Print full message.
    print(userInfo)
    Messaging.messaging().appDidReceiveMessage(userInfo)
    completionHandler()
}

}

在应用委托中实现以下方法:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler(UNNotificationPresentationOptions.alert)
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: 

使用下面的代码

[UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        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 })
            } else {
                let settings: UIUserNotificationSettings =
                    UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
                application.registerUserNotificationSettings(settings)
            }
            application.registerForRemoteNotifications()
        }