Talha Ahmad Khan
Talha Ahmad Khan

Reputation: 3476

Swift: Getting Data from Remote notification

I have a messaging app, which gets data from server through push notification. In the following image, you can see the process and also check where it gets faulted:enter image description here

I have researched a lot about this problem but not getting a universal solution.

One solution I get is to use silent notification , discussed Here , to get data before it is shown and save it. But I didn't find how to show notification from app delegate once I received silent notification.

Kindly correct me if I am conceptually wrong somewhere.

Update: One of problem is that the application:didReceiveRemoteNotification:fetchCompletionHandler: is only called when

  1. app is in foreground
  2. user clicks the notification

But when user doesn't click the notification, application:didReceiveRemoteNotification:fetchCompletionHandler: is not called, and I can't find a way to save the data, that is present in notification.

Upvotes: 3

Views: 4100

Answers (2)

Austin Michael
Austin Michael

Reputation: 490

There are two cases:

  1. Background
  2. Closed State

If the app is in Background State, you have to enable Background Fetch, then this method will be called when the app is in Background application:didReceiveRemoteNotification:fetchCompletionHandler:

When the app is closed or killed by the user the above method not gonna work, for that you can use the VoIP technique.

didReceiveIncomingPushWithPayload method will be called whenever Remote Notification arrives

You can find more details about VoIP here

Upvotes: 3

Abirami Bala
Abirami Bala

Reputation: 790

Your question is "To get data from Remote notification while the App is in foreground" if im correct, You can use these two methods to get data from Remote notifications for background and foreground app modes.

//  Notification will present call back
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([.alert, .sound, .badge])

    // Handle your data here
    print("Notification data: \(notification.request.content.userInfo)")
}

@available(iOS 10.0, *)
//  Notification interaction response call back
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {

    // Handle your data here
    print("Notification data: \(response.notification.request.content.userInfo)")

}

Upvotes: 3

Related Questions