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

Running ios local notification only once after first use

我想 运行 在用户第一次停止使用该应用程序一小时后发出本地通知。我在名为 LocalNotifications 的 class 中设置了以下函数:

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")
}