当应用程序打开时,Swift ios推送通知notif not woking但是当app关闭时它正在工作

时间:2018-03-26 07:01:10

标签: ios swift apple-push-notifications

如何处理即使应用程序打开或关闭时也会通知的推送通知。我有ff。下面的代码及其在应用程序关闭时通知但在应用程序打开时不通知。我在下面提供了我的源代码。谢谢。非常感谢。如何处理推送通知即使应用程序打开或关闭它也会通知。我有ff。下面的代码及其在应用程序关闭时通知但在应用程序打开时不通知。我在下面提供了我的源代码。谢谢。非常感谢。

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)")
            }
        }
    }



}

3 个答案:

答案 0 :(得分:1)

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()
        }

答案 1 :(得分:0)

请使用此代码

       @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()
}

}

答案 2 :(得分:0)

在app delegate上实现以下方法:

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