代码之家  ›  专栏  ›  技术社区  ›  Abhishek Thapliyal

iOS远程通知句柄应用程序活动案例

  •  0
  • Abhishek Thapliyal  · 技术社区  · 7 年前

    我已经启用了后台模式的远程通知。

    因此,我需要处理这样一种情况:应用程序位于前台,通知到达。因此,只有当用户点击通知时,它才应该执行像打开另一个视图这样的操作。

    但就我而言,它是自动发生的。

    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 回复  |  直到 7 年前
        1
  •  0
  •   Abhishek Thapliyal    7 年前

    对我来说,这个方法在前面被调用过

    func application(_ application: UIApplication,
                     didReceiveRemoteNotification userInfo: [AnyHashable : Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    
        completionHandler(.newData)
    }
    

    因为我还没有设定 联合国信息中心 在AppDelegate中。

    UNUserNotificationCenter.current().delegate = self
    

    顺便 @迪米特里斯 我添加了一些建议,然后它调用了

    遗嘱 & 收到 APNS委托方法(iOS 10中引入的新委托方法)

    因此,现在我能够处理APN上的用户点击操作,就像点击它触发didReceive委托方法一样。

        2
  •  0
  •   marc_s MisterSmith    7 年前

    当通知到达时,您所指的方法将被调用,即当应用程序处于后台或前台时。

    但当用户点击通知时,情况并非如此。

    您需要为其分配一个代理 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()