Unable to open URL from notification action handler

I am trying to handle local notifications by opening a url in iOS 10 / Swift 3. I have one url assigned to the default action of a notification and another one assigned to a custom action button.

When the default action is triggered (clicking on the notification itself), the app successfully opens the URL. But when the action button is clicked the handler is called UNUserNotificationCenterDelegate

and canOpenURL

returns true, but the call to open the url fails.

This issue only occurs if the app is in the background or terminated while listening to the notification. If the app is in the foreground, both things work.

I also have a breakpoint in my delegate dedet application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:])

. It handles the default action, but not the custom action.

Do I need to do something differently when working with a custom action?

Here is the code:

func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
    switch response.actionIdentifier {
    case UNNotificationDefaultActionIdentifier:
        if let link = URL(string: "myapp://default"),
                    UIApplication.shared.canOpenURL(link) {
                    UIApplication.shared.open(link) { result in
                        print("open url result: \(result)") // this works!
            }
        }

    case "customActionIdentifier":
        if let link = URL(string: "myapp://custom"),
                    UIApplication.shared.canOpenURL(link) {
                    UIApplication.shared.open(link) { result in
                        print("open url result: \(result)") // this fails!
            }
        }
    }

    completionHandler()
}

      

+3


source to share


1 answer


I finally found the problem: when declaring a UNNotificationAction, you must include the UNNotificationActionOptions.foreground in the options array.



+5


source







All Articles