如何明智地删除重复的本地通知(Swift 4)?

时间:2018-03-27 21:35:11

标签: ios swift notifications local lifecycle

我有一个应用程序,从点击某个按钮(前景和背景)开始每30分钟触发一次本地通知。我学习了如何在点击另一个按钮或取消视图控制器时删除这些通知。这通过以下方式完成: 的 UNUserNotificationCenter.current()。removeAllPendingNotificationRequests() 它工作得很好。但是,如果用户通过在多任务模式下向上滑动强制退出(手动关闭)应用程序,这就是奇怪的事情开始发生的时候。默认情况下,已终止的应用程序不会删除那些待处理的推送通知,即使应用程序已关闭,它们也会继续运行。

我学到的是应用程序生命周期中有几个状态可以杀死应用程序。因此,App Delegate中有几种方法可以用来触发提到的代码来删除通知(否则它们会继续发送)。

因此,当我们在前台并点击主页按钮(或用iPhone X向上滑动)切换到多任务模式(在活动应用程序之间选择或删除它们)时,这是applicationWillResignActive的时间 - 我们可以开始观察应用终止在这里(可能通过观察applicationWillTerminate并使用某种方法作为选择器)并在终止时删除这些通知(奇怪的是,applicationWillTerminate并不总是单独工作)。

但是,如果您切换到另一个应用程序然后返回多任务模式,则此次应用程序处于后台模式(非活动模式)。因此,当应用程序已处于后台模式时,似乎无法触发某些方法并观察某些事情。我不知道有没有?在这种情况下,applicationDidEnterBackground也不起作用。一切都以“来自调试器的消息结束:由于信号9”

而终止

那么,当您的应用处于后台模式并且即将被用户终止时,如何删除所有待处理通知?如果它处于后台模式并且不会被用户终止,则通知需要保持活动状态。 如果有解决方案,请帮忙。或者,当视图控制器被解除时(它不是应用程序中的唯一和主视图控制器)以及用户在非活动状态或后台状态下终止/关闭应用程序时,有更好的方法可以删除待处理(活动)本地通知吗?谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

您可以选择何时应用即将变为非活动状态:

func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

在您的情况下,您应该删除所有这些通知,并将其再次添加到补充它们的其他功能中,例如:

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

我认为在UIViewController生命周期方法中添加和删除通知是一种很好的做法,而不是在应用级生命周期中