我启用了带有后台模式的远程通知。
因此,我需要处理一个案例,其中应用程序在前台和通知到达。因此,只有当用户点击Notification时,它才应该执行类似于打开另一个视图的操作。
但在我的情况下,这是自动发生的。
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print("APNS didReceive with fetchCompletionHandler: \(userInfo)")
switch application.applicationState {
case .background, .inactive:
PushNotificationManager.shared.handle(info: userInfo)
case .active:
// TODO THIS ACTION SHOULD ONLY TRIGGER WHEN USER TAP NOTIFICATION
PushNotificationManager.shared.handle(info: userInfo)
}
completionHandler(.newData)
}我怎么才能让这一切成为可能?
注意:不是一个重复的问题,因为他们没有确切地说明这种情况
发布于 2019-03-15 15:37:20
当通知到达时,您所引用的方法将被调用,这将是当应用程序是背景或前景时。
但是,当用户点击通知时,情况就不是这样了。
您需要将委托分配给UNUserNotificationCenter.current().delegate,然后实现此方法- userNotificationCenter(_:didReceive:withCompletionHandler:)。
class NotificationHandler: NSObject, UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
Logger.log("didReceive notification: \(response.notification.request.content.userInfo)")
if response.actionIdentifier == UNNotificationDefaultActionIdentifier {
let userInfo = response.notification.request.content.userInfo
// Process the user info —
}
completionHandler()
}
}
// In `application(_ application:,didFinishLaunchingWithOptions:)`
// Note this is for clarity - you'd need to keep a strong reference to the NotificationHandler() or will get deallocated immediately.
UNUserNotificationCenter.current().delegate = NotificationHandler()发布于 2019-03-17 18:30:39
对我来说,这个方法是在前面调用的。
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
completionHandler(.newData)
}因为我还没有在UNUserNotificationCenter中设置AppDelegate的委托。
UNUserNotificationCenter.current().delegate = self与@Dimitris的建议一样,我添加了以下内容
willPresent & didReceive 委托方法( iOS 10中引入的新委托方法)
因此,现在我能够处理APNS上的用户tap操作,就像在APNS上触发didReceive委托方法一样。
https://stackoverflow.com/questions/55185064
复制相似问题