2

Using iOS13.4, XCode11.4, Swift5.2,

In my current App, I successfully managed to create a Local Notification. A banner is shown when the notification occurs. The banner is shown independently of App-state (i.e. opened App running in Foreground or Background or even if the App is completely closed). So far so good :)

Now my question: Can you disable App-opening mechanism when the user presses the Notification Banner ?

Currently, I am using the UNUserNotificationCenterDelegate's Delegate methods to complete the notification (i.e. run some custom code when the user presses the banner). (see code-snippet below)

However, I do not want the App to necessarily open up for doing the completion work ! This could be perfectly done in the background for better customer experience.

Is it possible to run some code when the banner gets pressed but do this without App opening ? And if yes, how ?

Here is the code snippet:

import UIKit

class MyViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let content = UNMutableNotificationContent()
        content.title = "My Notification Title"
        content.categoryIdentifier = UUID().uuidString
        var notificationIdentifier = "23224-23134-234234"
        var notificationDate = Date(timeInterval: 30, since: Date())
        let notificationTriggerKind = Calendar.current.dateComponents([.day, .month, .year, .hour, .minute, .second], from: notificationDate)
        let notificationTrigger = UNCalendarNotificationTrigger(dateMatching: notificationTriggerKind, repeats: false)
        let notificationRequest = UNNotificationRequest(identifier: notificationIdentifier, content: content, trigger: notificationTrigger)
        let notificationCenter = UNUserNotificationCenter.current()
        notificationCenter.delegate = self
        notificationCenter.add(notificationRequest) {(error) in if let error = error { print("error: \(error)") } }
    }
}

extension MyViewController: UNUserNotificationCenterDelegate {

    // kicks in when App is running in Foreground (without user interaction)
    func userNotificationCenter(_ center: UNUserNotificationCenter,
            willPresent notification: UNNotification,
            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        // ...do your custom code...
        completionHandler([.alert, .sound])
    }

    // kicks in when App is running in Foreground or Background
    // (AND App is open) AND user interacts with notification
    func userNotificationCenter(_ center: UNUserNotificationCenter,
        didReceive response: UNNotificationResponse, withCompletionHandler
        completionHandler: @escaping () -> Void) {

        // ... do your custom code ....
        return completionHandler()
    }
}
iKK
  • 6,394
  • 10
  • 58
  • 131

0 Answers0