如何解决首次使用后仅运行一次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")
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。