【发布时间】:2019-05-15 16:47:14
【问题描述】:
我正在实现具有以下目标的本地通知功能:
如果用户至少 7 天没有访问屏幕 X,则显示此通知。 只显示一次,即使用户在第一次显示通知后没有再次访问屏幕 X。
我目前的策略是安排在用户首次启动应用后 7 天触发通知。然后,如果用户在这 7 天之前访问屏幕 X,我会重新安排该通知,从而有效地将计时器重置为 7 天以上。我使用自定义类 (NotificationManager) 来管理通知的设置和调度。您可以假设NotificationManager 的实现没有错误。
这是我的 AppDelegate.swift:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// notification was never shown to the user
if firstEverAppLaunch {
NotificationManager.shared.schedule(notificationWithIdentifier: "remindUserToVisitScreenX")
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
if notification.request.identifier == "remindUserToVisitScreenX" {
UserDefaults.standard.set(true, forKey: "doNotShowNotificationAgain")
}
}
ScreenXController.swift
//.. some uninteresting code
override func viewWillAppear() {
// if user notification has never been shown, reschedule (i.e. reset) notification
if !UserDefaults.standard.bool(forKey: "doNotShowNotificationAgain") {
NotificationManager.shared.schedule(notificationWithIdentifier: "remindUserToVisitScreenX")
}
{
通过调用willPresent notification 函数,我当前的实现几乎可以正常工作。但是,如果通知在应用处于后台或非活动状态时到达,willPresent 将不会被调用,因此应用无法满足通知在整个生命周期内仅显示一次的要求应用程序。
例子:
用户一周未访问屏幕 X。应用程序处于非活动状态时会触发通知。用户关闭通知,然后启动应用程序,又一周没有访问屏幕 X。在那一周结束时,用户再次收到通知。
【问题讨论】:
标签: ios swift appdelegate localnotification unusernotificationcenter