如何设置每天上午8点至晚上8点之间的本地通知 [英] how to set local notifications between 8am and 8pm every day
问题描述
所以我对Swift还是很陌生,我目前正在启动应用程序后每30分钟设置一个重复计时器,但是我只想在上午8点至晚上8点之间发送通知.是否可以在没有为每个特定时间设置提醒的情况下执行此操作?
So I am very new to Swift and I'm currently setting a repeating timer every 30 min after the app was launched, but i would like to only send notification between 8 am and 8 pm. Is it possible to do this without setting a reminder for each specific time?
这是我目前正在这样做的方式.
This is how I'm currently doing this.
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)
}
推荐答案
不幸的是,您确实需要在8 am-8pm窗口中的每个30分钟间隔添加一个通知请求.您对这种方法有何厌恶?这是一个简单的for循环.除了使用UNTimeIntervalNotificationTrigger
之外,您还可以使用UNCalendarNotificationTrigger
.
Unfortunately you do need to add a notification request for each 30 minute interval in the 8am-8pm window. What is your aversion to this approach? It's a simple for-loop. Instead of using a UNTimeIntervalNotificationTrigger
you would use a 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)
}
这篇关于如何设置每天上午8点至晚上8点之间的本地通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!