如何设置每天早上8点到晚上8点之间的本地通知

how to set local notifications between 8am and 8pm every day

所以我是 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)
}

遗憾的是,您确实需要在上午 8 点到晚上 8 点之间每隔 30 分钟添加一个通知请求 window。您对这种方法有何反感?这是一个简单的for循环。您可以使用 UNCalendarNotificationTrigger.

而不是 UNTimeIntervalNotificationTrigger
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)
}