应用关闭时如何处理localNotifications

时间:2018-03-27 20:10:25

标签: ios swift4 uilocalnotification userinfo remote-notifications

我在这里搜索了所有问题,但没有解决方案。

我使用userInfo选项安排了localNotifications。 当应用程序处于前台时,通知到达并且可以完全处理系统自行调用的此功能。

  • 用于本地通知

    func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
    
        if application.applicationState == .active {
            return
        }
    
        //My implementation
    }
    
  • 用于远程通知

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
    
        if application.applicationState == .active {
            return
        }
    
        //My implementation
    }
    

但问题是,当app关闭时,这个函数不会被调用,我无法处理我需要的数据。

我已尝试在appDelegate中的该函数中获取userInfo:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    if let localUserInfo = launchOptions?[UIApplicationLaunchOptionsKey.localNotification] as? [AnyHashable: Any] {

        // My implementation
    } else if let remoteUserInfo = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [AnyHashable: Any] {

        // My implementation
    }
    return true
}

但是..没有用......

有人可以帮我吗?

提前致谢。

2 个答案:

答案 0 :(得分:1)

您是否已注册通知? 在didFinishLaunchingWithOptions()中:

    // Register Notifications
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: { granted, error in

                if granted {
                    print("User notifications are allowed")
                } else {
                    print("User notifications are NOT allowed")
                }
            })
            application.registerForRemoteNotification()
            UNUserNotificationCenter.current().delegate = self

然后你应该在UNUserNotificationCenterDelegate方法中捕获本地通知:

extension AppDelegate: UNUserNotificationCenterDelegate {

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

        completionHandler()
    }

}

答案 1 :(得分:0)

如果用户点击它是本地的还是远程的,您将在didFinishLaunchingWithOptions收到通知,否则您不会知道,除非将它们存储在服务器中并在每次打开时将其拉出应用程序

相关问题