1

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

我使用 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
    }
    

但问题是,当应用程序关闭时,这个函数没有被调用,我无法处理我需要的数据。

我试过在 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
}

但是..没有工作...

有人可以帮助我吗?

提前致谢。

4

2 回答 2

2

你注册通知了吗?在 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()
    }

}
于 2018-03-27T20:16:49.333 回答
0

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

于 2018-03-27T20:13:18.853 回答