无法打开来自通知操作处理程序的URL
问题描述:
我想通过在iOS 10/Swift 3上打开URL来处理本地通知。我有一个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()
}
答
我终于发现了问题:声明UNNotificationAction的时候,你必须包括UNNotificationActionOptions.foreground的选项阵列英寸
你救了我的命:) –