Receive data from the payload when a remote push notification arrives when my application is in the background or closed

I need to grab data from the payload when receiving a remote push notification, on iOS 9 I did this using the func function: didReceiveRemoteNotification On iOS 10 using swift 3.0 I implemented these 2 functions.

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{
print("\(notification.request.content.userInfo)")

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

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
{
print("User Info = ",response.notification.request.content.userInfo)

completionHandler()
}

the second fuction is executed only when the user touches the click

I need capture data when a push notification appears, when my application is in the background or even closed.

Sincerely. Hi

+4
source share
3 answers

push- , didFinishLaunchingWithOptions:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
   // Called when a notification is tapped and the app wasn't running, not in foreground neither in background. 
   if let userInfo = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [String: AnyObject]{
        // your logic here!
    }
}
+1
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    // Capture payload here something like:
    let appState = userInfo["appState"] as? String
    print(appState!)

    // Do something for every state
    if (application.applicationState == UIApplicationState.active){
        print("Active")

    }else if (application.applicationState == UIApplicationState.background){
        print("Background")


    }else if (application.applicationState == UIApplicationState.inactive){
        print("Inactive")

    }

    completionHandler(.noData)

}
+1

try to execute the didReceiveRemoteNotification function in iOS10:

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {

                   print(userInfo)

             }
0
source

Source: https://habr.com/ru/post/1656954/


All Articles