0

I'm using swift 3 and trying to read notifications in didReceiveRemoteNotification

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

It's working while app is running but not printing anything while app is background (inactive). How can I read notifications while app is in background (inactive).

droidBomb
  • 850
  • 5
  • 8
Agent Smith
  • 136
  • 10
  • check this question about silent notifications: https://stackoverflow.com/questions/36694963/what-is-silent-push-notification-when-does-the-device-receive-it – Moayad Al kouz Nov 12 '18 at 09:43

1 Answers1

0

After taking appropriate permissions for the background notifications in your app and adopting UNUserNotificationCenterDelegate in the appropriate viewController. You can implement this method to trigger notifications in the background and take actions to perform any action from the notification. To perform any action from the notification you need to adopt the function userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void).

func startNotifications() {




        let notificationCenter = UNUserNotificationCenter.current()

// to include any action in the notification otherwise ignore it.

        let action = UNNotificationAction(identifier: "ActionRelatedIdentifier", title: "Name which you want to give", options: [.destructive, .authenticationRequired])

        let category = UNNotificationCategory(identifier: "CategoryName", actions: [stopAction], intentIdentifiers: [],  options: [])

        notificationCenter.setNotificationCategories([category])

        let content = UNMutableNotificationContent()
        content.title = "Your Title"
        content.body = "Message you want to give"
        content.sound = UNNotificationSound.default



      // To trigger the notifications timely and repeating it or not  
           let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1.5, repeats: false)





        content.categoryIdentifier = "CategoryName"



            print("Notifications Started")

            let request = UNNotificationRequest(identifier: "NotificationRequestIdentifier", content: content, trigger: trigger)

            notificationCenter.add(request, withCompletionHandler: { (error) in
                if error != nil {
                    print("Error in notification : \(error)")
                }
            })


    }

Disclaimer: do apply the solution according to your need and ask if anything wrong happens. This code is for triggering background notifications.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Anand Nigam
  • 128
  • 3
  • 9