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

时间:2020-10-29 19:13:50

标签: ios swift uilocalnotification

我想在用户首次停止使用该应用程序一小时后运行本地通知。我在名为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()

}

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

如何让它只运行一次?

1 个答案:

答案 0 :(得分:0)

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