如何在每天早上 8 点到晚上 8 点之间设置本地通知
Posted
技术标签:
【中文标题】如何在每天早上 8 点到晚上 8 点之间设置本地通知【英文标题】:how to set local notifications between 8am and 8pm every day 【发布时间】:2020-05-04 12:47:25 【问题描述】:所以我对 Swift 很陌生,我目前在应用程序启动后每 30 分钟设置一个重复计时器,但我只想在上午 8 点到晚上 8 点之间发送通知。是否可以在不为每个特定时间设置提醒的情况下做到这一点?
这就是我目前的做法。
override func viewDidLoad()
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.requestAuthorization(options: [.alert, .sound]) (granted, error ) in
// enable or disable if needed.
if granted
print("We have permission to send notifications")
else
print("We don't have the option to send notifications")
notificationCenter.removeAllDeliveredNotifications()
notificationCenter.removeAllPendingNotificationRequests()
// The actual notification the user will receive
let notification = UNMutableNotificationContent()
notification.title = "You should have some water"
notification.body = "It has been a long time since you had some water, why don't you have some."
notification.categoryIdentifier = "reminder"
notification.sound = .default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: (60*30), repeats: true)
let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: uuidString, content: notification, trigger: trigger)
notificationCenter.add(request, withCompletionHandler: nil)
【问题讨论】:
【参考方案1】:很遗憾,您确实需要在上午 8 点至晚上 8 点窗口中每隔 30 分钟添加一个通知请求。您对这种方法有何反感?这是一个简单的for循环。而不是使用UNTimeIntervalNotificationTrigger
,而是使用UNCalendarNotificationTrigger
。
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.removeAllDeliveredNotifications()
notificationCenter.removeAllPendingNotificationRequests()
let startHour = 8
let totalHours = 12
let totalHalfHours = totalHours * 2
for i in 0...totalHalfHours
var date = DateComponents()
date.hour = startHour + i / 2
date.minute = 30 * (i % 2)
print("\(date.hour!):\(date.minute!)")
let notification = UNMutableNotificationContent()
notification.title = "You should have some water"
notification.body = "It has been a long time since you had some water, why don't you have some."
notification.categoryIdentifier = "reminder"
notification.sound = .default
let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)
let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: uuidString, content: notification, trigger: trigger)
notificationCenter.add(request, withCompletionHandler: nil)
【讨论】:
谢谢。因此,如果我想给用户更改警报频率的选项,我需要更改 date.minute?我了解如何使用它来更改开始和结束时间,但您能帮我了解如何使其更可定制吗?我希望能够自定义警报的频率以及开始和结束。 @PetterBraka 我愿意。但是,我认为这个问题超出了这个问题的范围。也许开始一个新的。但基本上,您将遍历间隔而不是totalHalfHours
,并根据当前间隔计算小时和分钟。
好的,谢谢。我想我明白你的意思。我会试试看能不能成功。以上是关于如何在每天早上 8 点到晚上 8 点之间设置本地通知的主要内容,如果未能解决你的问题,请参考以下文章
人的差别在于业余时间,而一个人的命运决定于晚上8点到10点之间
电脑设置了每天下午五点自动关机,第二天早上电脑为啥还是开着的?