无法从通知操作处理程序打开URL

时间:2017-04-10 23:58:16

标签: ios ios10 uilocalnotification openurl unusernotificationcenter

我正在尝试通过在iOS 10 / Swift 3上打开URL来处理本地通知。我有一个URL分配给通知的默认操作,另一个分配给自定义操作按钮。

当触发默认操作(点击通知本身)时,应用程序会成功打开URL。但是,当点击操作按钮时,将调用UNUserNotificationCenterDelegate处理程序并且canOpenURL返回true,但是打开URL的调用失败。

仅当应用在后台或在点击通知时终止时,才会出现此问题。如果应用程序位于前台,则两种情况都有效。

我的app委托的application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:])方法中也有一个断点。它命中默认操作但不适用于自定义操作。

处理自定义操作时,是否需要采取不同的操作?

以下是代码:

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()
}

1 个答案:

答案 0 :(得分:6)

我终于找到了问题:在声明UNNotificationAction时,你必须在options数组中包含UNNotificationActionOptions.foreground。