首次使用后仅运行一次ios本地通知

问题描述

我想在用户首次停止使用该应用程序一小时后运行本地通知。我在名为localnotifications的类中设置了以下函数

static func setupNewUserNotifications() {
    // SCHEDULE NOTIFICATION 1 HOUR AFTER FirsT USE
    
    let content = UNMutableNotificationContent()
    content.title = "Title"
    content.body = "Content."
    content.sound = UNNotificationSound.default

    // show this notification 1 hr from Now
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3600,repeats: false) 

    // setup identifier
    let request = UNNotificationRequest(identifier: "NewUser",content: content,trigger: trigger)
    
    // add our notification request
    UNUserNotificationCenter.current().add(request)
}

然后我从AppDelegate调用它:

func applicationWillResignActive(_ application: UIApplication) {

    localnotifications.setupNewUserNotifications()

}

问题是,这会在用户每次离开并经过一个小时后触发通知

如何让它只运行一次?

解决方法

UserDefaults中设置标记,如果标记为true,则不发送通知,否则发送通知并将标记写为true

static func setupNewUserNotifications() {

    let defaults = UserDefaults.standard

    // Check for flag,will be false if it has not been set before
    let userHasBeenNotified = defaults.bool(forKey: "userHasBeenNotified")

    // Check if the flag is already true,if it's not then proceed
    guard userHasBeenNotified == false else {
        // Flag was true,return from function
        return
    }

    // SCHEDULE NOTIFICATION 1 HOUR AFTER FIRST USE
    let content = UNMutableNotificationContent()
    content.title = "Title"
    content.body = "Content."
    content.sound = UNNotificationSound.default

    // show this notification 1 hr from now
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3600,repeats: false)

    // setup identifier
    let request = UNNotificationRequest(identifier: "NewUser",content: content,trigger: trigger)

    // add our notification request
    UNUserNotificationCenter.current().add(request)

    // Set the has been notified flag
    defaults.setValue(true,forKey: "userHasBeenNotified")
}