5

I am trying to handle local notifications by opening a URL on iOS 10 / Swift 3. I have one URL assigned to the notification's default action and another assigned to a custom action button.

When the default action is triggered (tapping on the notification itself), the app opens the URL successfully. But when the action button is tapped, the UNUserNotificationCenterDelegate handler is called and canOpenURL returns true, but the call to open the URL fails.

This issue happens only if the app is in the background or terminated when the notification is tapped. If the app is in the foreground both cases work.

I also have a breakpoint in my app delegate's application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) method. It hits for the default action but not for the custom action.

Do I need to do something differently when handling 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()
}
mfaani
  • 33,269
  • 19
  • 164
  • 293
ewerx
  • 403
  • 4
  • 10

1 Answers1

12

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

ewerx
  • 403
  • 4
  • 10