在后台以及终止应用程序时未收到推送通知

时间:2018-10-15 08:30:45

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

我在我的应用程序中实现了推送通知功能,当应用程序处于前台和后台时会捕获通知,但是当应用程序不处于活动状态时,如果我收到任何通知,我都无法捕获它。以下是我的代码。在我的应用程序处于非活动状态时,是否缺少我无法收到通知的任何代码行?

@UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {

        var window: UIWindow?

        var badgeCount = 0


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





                  if #available(iOS 10.0, *) {
                UNUserNotificationCenter.current().delegate = self

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

               // application.registerUserNotificationSettings(authOptions)
                    UNUserNotificationCenter.current().delegate = self

                  //  Messaging.messaging().remoteMessageDelegate = self
                 //   Messaging.messaging().delegate = self

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

                application.registerUserNotificationSettings(settings)
            }

            application.registerForRemoteNotifications()

            // [END register_for_notifications]

            Messaging.messaging().delegate = self
            Messaging.messaging().shouldEstablishDirectChannel = true
            // [START add_token_refresh_observer]
            // Add observer for InstanceID token refresh callback.
    //        NotificationCenter.default.addObserver(self,
    //                                               selector: #selector(self.tokenRefreshNotification),
    //                                               name: ,
    //                                               object: nil)
            // [END add_token_refresh_observer]
                  FirebaseApp.configure()
            Messaging.messaging().subscribe(toTopic: "*****");
            //changes for localization
            Localization.switchLanguages()



            return true
        }

        // [START receive_message]
        func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
                   if let messageID = userInfo[gcmMessageIDKey] {
                print("Message ID: \(messageID)")
            }

            print("From func -1 \(userInfo)")


            //showPushNotification(message: userInfo["message"] as! String)
            Messaging.messaging().appDidReceiveMessage(userInfo)
            // Print full message.
        }

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

      //      let state: UIApplicationState = UIApplication.shared.applicationState


            if let messageID = userInfo[gcmMessageIDKey] {
                print("Message ID: \(messageID)")
            }

            // Print full message.
            print(userInfo)

       //     showPushNotification(message: userInfo["body"] as! String)
            Messaging.messaging().appDidReceiveMessage(userInfo)
            completionHandler(UIBackgroundFetchResult.newData)
            }
        // [END receive_message]

        // [START refresh_token]
        func tokenRefreshNotification(_ notification: Notification) {

            connectToFcm()

            if let refreshedToken = InstanceID.instanceID().token() {
                print("InstanceID token: \(refreshedToken)")
                Messaging.messaging().subscribe(toTopic: "******");



                let loggedInUser = getLoggedInUser();
                if(loggedInUser != nil && !(loggedInUser?.isEmpty)!){
                    Messaging.messaging().subscribe(toTopic: GlobalData.sharedInstance.getLoggedInEmployee().userID + "-ios")
                    Messaging.messaging().subscribe(toTopic: "*******");

                }
            }

            // Connect to FCM since connection may have failed when attempted before having a token.
        }
        // [END refresh_token]

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

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

            Messaging.messaging().connect { (error) in
                if error != nil {
                    print("Unable to connect with FCM. \(error)")
                } else {
                    print("Connected to FCM.")
                }
            }
        }
        // [END connect_to_fcm]



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


        func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

            print("APNs token retrieved: \(deviceToken)")

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

        }

        fileprivate func convertDeviceTokenToString(_ deviceToken:Data) -> String {
            //  Convert binary Device Token to a String (and remove the <,> and white space charaters).

            var deviceTokenStr = deviceToken.description.replacingOccurrences(of: "<", with: "")

            deviceTokenStr = deviceTokenStr.replacingOccurrences(of: ">", with: "")
            deviceTokenStr = deviceTokenStr.replacingOccurrences(of: " ", with: "")

            return deviceTokenStr
        }


        func applicationWillResignActive(_ application: UIApplication) {

        }

        func applicationDidEnterBackground(_ application: UIApplication) {

           // FIRMessaging.messaging().disconnect()
            print("Disconnected from FCM.")
        }

        func applicationWillEnterForeground(_ application: UIApplication) {

            NotificationCenter.default.post(name: Notification.Name(rawValue: "DashboardOperation"), object: self)

        }

        func applicationDidBecomeActive(_ application: UIApplication) {
            connectToFcm()
            application.applicationIconBadgeNumber = badgeCount
        }



        func applicationWillTerminate(_ application: UIApplication) {
                    self.saveContext()
        }

        // MARK: - Core Data stack

        lazy var applicationDocumentsDirectory: URL = {
            let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
            return urls[urls.count-1]
        }()

        lazy var managedObjectModel: NSManagedObjectModel = {
            let modelURL = Bundle.main.url(forResource: "Vachan", withExtension: "momd")!
            return NSManagedObjectModel(contentsOf: modelURL)!
        }()

        lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
              let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
            let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
            var failureReason = "There was an error creating or loading the application's saved data."
            do {
                try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
            } catch {
                var dict = [String: AnyObject]()
                dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
                dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?

                dict[NSUnderlyingErrorKey] = error as NSError
                let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)

                NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
                abort()
            }

            return coordinator
        }()

        lazy var managedObjectContext: NSManagedObjectContext = {

            let coordinator = self.persistentStoreCoordinator
            var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
            managedObjectContext.persistentStoreCoordinator = coordinator
            return managedObjectContext
        }()

        // MARK: - Core Data Saving support




        @available(iOS 10.0, *)
        lazy var persistentContainer: NSPersistentContainer = {

        let container = NSPersistentContainer(name: "NotificationModel")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error {

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

    func saveContext () {
        if #available(iOS 10.0, *) {
            let context = persistentContainer.viewContext
            if context.hasChanges {
                do {
                    try context.save()
                } catch {

                    let nserror = error as NSError
                    fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
                }
            }
        } else {
            // Fallback on earlier versions
        }


    }
    }
    // [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

            // Print message ID.
            if let messageID = userInfo[gcmMessageIDKey] {
                print("Message ID: \(messageID)")
            }
            print("\(notification.request.content.body)")

            completionHandler([.alert,.sound,.badge])
        }

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

            // Print full message.
            print(userInfo)
            let mainStoryboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
            let initialViewController: UIViewController = mainStoryboard.instantiateViewController(withIdentifier: "VANotificationTableViewController") as! VANotificationViewController

    //        self.window = UIWindow(frame: UIScreen.main.bounds)
            self.window?.rootViewController = initialViewController
    //        self.window?.makeKeyAndVisible()
            //showPushNotification(message: response.notification.request.content.body)

            completionHandler()
        }
    }

    // [END ios_10_message_handling]
    // [START ios_10_data_message_handling]
    extension AppDelegate : MessagingDelegate {
        // Receive data message on iOS 10 devices while app is in the foreground.
        func applicationReceivedRemoteMessage(_ remoteMessage: MessagingRemoteMessage) {

            let userInfo = remoteMessage.appData
            // Print message ID.
            if let messageID = userInfo[gcmMessageIDKey] {
                print("Message ID: \(messageID)")
            }

            // Print full message.
            print("From FIRMessaging Delegate \(userInfo)")

              showPushNotification(notificationBody: (remoteMessage.appData  as! Dictionary<String, Any>))

        }


        func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
            print(fcmToken)
        }

        func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        showPushNotification(notificationBody: (remoteMessage.appData  as! Dictionary<String, Any>))
        }


        func messaging(_ messaging : Messaging , didRefreshRegistationToken fcmToken : String) {
            print("Firebase token: \(fcmToken)")
        }


    }

0 个答案:

没有答案