2

我在 UNNotificationContentExtension 的实现上启用了用户交互。用户完成与 UNNotificationContentExtension / ondemand 的交互后,如何打开应用程序?

请注意,UNNotificationAction 专门用于预编程操作,例如这些. 我不能使用它,例如,如果我想要 UIButton 上的 .touchUpInside 操作的结果来打开应用程序。

4

1 回答 1

2

解雇:self.extensionContext?.dismissNotificationContentExtension()

打开应用程序:self.extensionContext?.performNotificationDefaultAction()

(我对此进行了测试,这对我有用。解除操作并没有完全解除通知,只是解除了上下文。performNotificationDefaultAction 解除了通知并打开了应用程序。至少对我来说,这在文档中并不明显,并采取了我有点找。)

在您的内容扩展中,为下面的 UNNotificationContentExtension 实现可选功能,以便向您的应用程序发送响应。

func didReceive(_ response: UNNotificationResponse, completionHandler completion: @escaping (UNNotificationContentExtensionResponseOption) -> Void) {

    switch response.actionIdentifier {
    case UNNotificationDismissActionIdentifier:
        // Clearest explanation from Microsoft: https://docs.microsoft.com/en-us/dotnet/api/UserNotificationsUI.UNNotificationContentExtensionResponseOption?view=xamarin-ios-sdk-12
        // Indicates that the notification interface will be dismissed, and that the content extension will handle the action.
        completion(.dismiss)
        // completion(.doNotDismiss)
    case UNNotificationDefaultActionIdentifier:
        // Default action stuff.
        // Let's say the user executed default action, we want to dismiss and forward the action to the app delegate.
        completion(.dismissAndForwardAction)
        break
    default:
        break
    }

要接收响应,请在您的应用委托中实现 UNUserNotificationCenterDelegate 协议的以下功能。您可以使用与上述相同的 switch 语句。

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    // Received user info is given by response.notification.request.content.userInfo.
}

我们可以读取 userInfo 并根据委托中的内容采取行动。但是,如果该操作根据用户在通知界面中的交互而发生变化怎么办?例如,通知的内容是相同的,但是用户在您的界面中按下了一个显示“打开 URL”的按钮,而不是另一个显示“采取行动”的按钮。我们无法从界面打开 URL,因此我们必须以某种方式将此操作(而不是其他标准操作)转发给应用程序。

我不确定如何做到最好[1]。如果您有解决方案,请在下方评论!我目前正在使用 UIPasteboard,它允许在 Apple 设备上的不同应用程序之间进行共享。这可能是为数不多的解决方案之一,因为您的主应用程序和通知内容扩展是完全不同的目标。以下是粘贴板的简单 CRUD 操作。

let pasteboard = UIPasteboard.init(name: "myApp", create: true)
  • C:pasteboard?.setValue("actionToTake", forKey: "setNotificationAction")
  • 回复:pasteboard?.value(forKey: "setNotificationAction") as? String
  • U:同C
  • 丁:pasteboard?.setValue(nil, forKey: "setNotificationAction")

在上下文界面中设置;读入 AppDelegate。

[1] 可以做一个云解决方案,但并不理想。此外,UserDefaults 不起作用(因此,Pasteboard;尝试了 UserDefaults)。

于 2019-06-22T21:32:03.727 回答