【问题标题】:Cannot open URL from notification action handler无法从通知操作处理程序打开 URL
【发布时间】:2017-09-06 04:11:27
【问题描述】:

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

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

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

我的应用程序委托的 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()
}

【问题讨论】:

    标签: ios ios10 uilocalnotification openurl unusernotificationcenter


    【解决方案1】:

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

    【讨论】:

    • 你救了我的命 :)
    猜你喜欢
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-11
    相关资源
    最近更新 更多