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

问题描述 投票:0回答:1

所以我对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)
}
swift localnotification unusernotificationcenter
1个回答
1
投票

不幸的是,你确实需要为8am-8pm窗口的每30分钟间隔添加一个通知请求。你对这种方式有什么反感?这是一个简单的for-loop。而不是使用一个 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)
}
© www.soinside.com 2019 - 2024. All rights reserved.