ios notification not working on background, foreground

牧云@^-^@ 提交于 2021-02-05 09:33:09

问题


I want to use notification when app pause mode(foreground) and app kill (background),

Only notification working on when the app opens (app running). I used this on Flutter project.

enable Background Mode(Background fetch, Remote notifications) and push notification

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
       
        Messaging.messaging().delegate = self
       
        
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().delegate = self
            
            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {granted, error in print("Permission granted: \(granted)") })
        }else{
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }
        GeneratedPluginRegistrant.register(with: self)
        application.registerForRemoteNotifications()
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
    
    func connectToFcm() {
        Messaging.messaging().shouldEstablishDirectChannel = true
    }
    
    override func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
     
        createNotifications(userInfo: userInfo)
    }
    
    override func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                              fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
     
        let state : UIApplicationState = application.applicationState
        if (state == .inactive || state == .background) {
          
            createNotifications(userInfo: userInfo)
        } else {
          
            createNotifications(userInfo: userInfo)
        }
        completionHandler(UIBackgroundFetchResult.newData)
    }
    
    override func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
      //
    }
    
    override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
     
        connectToFcm()
    }
    
    @available(iOS 10.0, *)
    override func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
      
        completionHandler([.alert, .badge, .sound])
    }
    
        override func applicationDidBecomeActive(_ application: UIApplication) {
             UIApplication.shared.applicationIconBadgeNumber = 0
           
             connectToFcm()
         }
    
    override func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        
      
        completionHandler(.newData)
        
    }
    
    func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
        
        //         if let token = InstanceID.instanceID().token() {
        //             AppDelegate.DEVICE_ID = token
        //             print("*********")
        //             print("Token Instance: \(token)")
        //             print("*********")
        //         }
       
        connectToFcm()
    }
    
    //    override func applicationDidEnterBackground(_ application: UIApplication) {
    //        Messaging.messaging().shouldEstablishDirectChannel = false
    //        print("Disconnect FCM")
    //    }
    
    func createNotifications(userInfo: [AnyHashable: Any]) {
        if #available(iOS 10.0, *) {
         
            let notificationContent = UNMutableNotificationContent()
            notificationContent.title = userInfo["title"] as! String
            notificationContent.body = userInfo["body"] as! String
            notificationContent.sound = UNNotificationSound.default()
            notificationContent.badge = NSNumber(integerLiteral: UIApplication.shared.applicationIconBadgeNumber + 1)
            notificationContent.threadIdentifier = userInfo["groupKey"] as! String
            if #available(iOS 12.0, *) {
                notificationContent.summaryArgument = userInfo["groupKey"] as! String
            } else {
                // Fallback on earlier versions
            }

            let request = UNNotificationRequest(identifier: UUID.init().uuidString, content: notificationContent, trigger: nil)
            let center = UNUserNotificationCenter.current()
            center.add(request) { (error: Error?) in
                if let theError = error {
                    print("error \(theError)")
                }
            }
        }
    }
}

extension AppDelegate : MessagingDelegate{
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
     
        let dataDict:[String: String] = ["token": fcmToken]
        NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
    }
 
}

payload looks like this

const payload = {
  "data": {
      title: title,
      body: contentMessage,
      groupKey : groupKey
  },

  token: pushToken,

}

来源:https://stackoverflow.com/questions/63598194/ios-notification-not-working-on-background-foreground

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!