我已启用具有后台模式的远程通知。
因此,我需要处理一个应用程序处于前台并且通知到达的情况。因此,仅当用户点击通知时,它才应执行打开另一个视图之类的操作。
但是对于我来说,它是自动发生的。
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)
}
我如何使之成为可能?
注意:不是一个重复的问题,因为他们没有确切说明此情况
答案 0 :(得分:0)
您要引用的方法将在通知到达时调用,即应用程序为后台或前台时。
但是当用户点击通知时情况并非如此。
您需要将委托分配给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()
答案 1 :(得分:0)
对我来说,此方法被称为
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
completionHandler(.newData)
}
因为我尚未在AppDelegate中设置 UNUserNotificationCenter 的委托。
UNUserNotificationCenter.current().delegate = self
我添加了 @Dimitris 的建议,然后将其称为
willPresent 和 didReceive APNS委托方法(iOS 10中引入了新的委托方法)
因此,现在我能够在APNS上处理用户点击操作,因为点击它会触发didReceive委托方法。