问题描述
背景
我有一个支持多个窗口的应用程序(iPadOS 13+),我想知道响应用户点击通知的正确方式。我想根据用户点击的通知设置 UI。
我像这样在 UNUserNotificationCenterDelegate
的共享实例上设置 UNUserNotificationCenter
属性:
func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().delegate = self
return true
}
我符合 UNUserNotificationCenterDelegate
并实现以下方法。当用户与通知交互时总是触发此方法:
func userNotificationCenter(_ center: UNUserNotificationCenter,didReceive response: UNNotificationResponse,withCompletionHandler completionHandler: @escaping () -> Void) {
// This gets called whenever a notification is tapped,dismissed or a custom action is performed by the user from the system Notification Center UI.
// Should my UI setup code live here?
completionHandler()
}
在标题为 Targeting Content with Multiple Windows 的会话中,Apple 解释说,当您的应用支持多个窗口时,系统将使用以下属性来帮助确定当用户点击通知时将向用户显示哪个窗口:
>// An identifier for the content of the notification used by the system to customize the scene to be activated when tapping on a notification.
response.notification.request.content.targetContentIdentifier
最终,UIKit 没有约定在用户点击通知时将打开哪个场景(窗口),但它会尽力打开我指定的最匹配 {{1 }} 用于通知。
如果用户在我的应用程序终止时点击通知,那么在我的 targetContentIdentifier
上调用以下函数时,我将能够访问有关 SceneDelegate
中的通知点击的信息:
SceneDelegate
如果我的应用程序未终止,则不会调用此函数。
问题
- 我应该如何确定 UIKit 将打开哪个场景,以便在正确的窗口中设置我的 UI?
解决方法
看起来 UNNotificationResponse
有一个名为 targetScene
的属性,应根据此属性确定要更新的场景:
https://developer.apple.com/documentation/usernotifications/unnotificationresponse/3255096-targetscene