首次使用后仅运行一次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")
}

最新更新