didReceiveRemoteNotification function doesn't called with FCM notification server

后端 未结 6 953
隐瞒了意图╮
隐瞒了意图╮ 2020-12-11 10:00

I\'m using FCM server for remote notifications, it worked perfectly with sending and receiving notifications.

My problem is when the device is in the background, thi

6条回答
  •  甜味超标
    2020-12-11 10:19

    Step 1 – Add framework

    import UserNotifications
    

    Step 2 – Inherit AppDelegate with UNUserNotificationCenterDelegate

    final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {}
    

    Step 3 – Make appropriate changes for registerPushNotifications and call it didFinishLaunchingWithOptions

    private func registerPushNotifications() {
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.currentNotificationCenter().delegate = self
            UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions([.Badge, .Sound, .Alert], completionHandler: { granted, error in
    
                if granted {
                    UIApplication.sharedApplication().registerForRemoteNotifications()
                } else {
                        // Unsuccessful...
                }
              })
        } else {
            let userNotificationTypes: UIUserNotificationType = [.Alert, .Badge, .Sound]
            let settings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil)
            UIApplication.sharedApplication().registerUserNotificationSettings(settings)
            UIApplication.sharedApplication().registerForRemoteNotifications()
       }
    }
    

    Step 4 – Implement new handlers

        // leave this for older versions 
    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
    }
    
    // For iOS10 use these methods and  pay attention how we can get userInfo
    // Foreground push notifications handler
    @available(iOS 10.0, *)
    func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {
        if let userInfo = notification.request.content.userInfo as? [String : AnyObject] {
            // Getting user info
        }
        completionHandler(.Badge)
     }
    
    // Background and closed  push notifications handler
    @available(iOS 10.0, *)
    func userNotificationCenter(center: UNUserNotificationCenter, didReceiveNotificationResponse response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void)  {
        if let userInfo = response.notification.request.content.userInfo as? [String : AnyObject] {
            // Getting user info
        }
        completionHandler()
    }
    

提交回复
热议问题