gpt4 book ai didi

ios - 每天和每半小时重复一次 UNNotifications

转载 作者:行者123 更新时间:2023-11-28 15:27:05 26 4
gpt4 key购买 nike

我想在用户选定的时间之间向用户显示本地通知,并每半小时重复一次该通知,直到选定的时间限制到来,并且每天重复一次该通知。我用过这段代码

let components = calendar.dateComponents(in: .current, from: date)
var triggerDate = DateComponents()
triggerDate.hour = components.hour
triggerDate.minute = components.minute
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)

但这只会在用户选择的特定时间每天重复通知,但我也想从那个特定时间开始每半小时重复一次。我使用了 UNNotifications。任何帮助将不胜感激。谢谢

最佳答案

如果您想在所选时间之间每半小时显示一次本地通知,则必须使用不同的通知标识符为每个小时设置不同的通知:

var dateStart = "Pass Your Start Date for Notification."
let dateEnd = "Pass Your End Date for Notification."

//Check Start Date is less then End Date is not.
while dateStart < dateEnd {

dateStart = dateStart.addingTimeInterval(0.5 * 60 * 60) //Add half an hour to start time

//Schedule notification With body and title.
scheduleNotification(at: dateStart, body: "Show Me", titles: "Remainder")

}

通过以下函数实现通知:

//Schedule Notification with Daily bases.
func scheduleNotification(at date: Date, body: String, titles:String) {

let triggerDaily = Calendar.current.dateComponents([.hour,.minute,.second], from: date)

let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)

let content = UNMutableNotificationContent()
content.title = titles
content.body = body
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "todoList"

let request = UNNotificationRequest(identifier: "NotificationAt-\(date))", content: content, trigger: trigger)

UNUserNotificationCenter.current().delegate = self
//UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print("Uh oh! We had an error: \(error)")
}
}
}

在 dateStart 变量中传递开始 Date,在 dateEnd 变量中传递 Date 结束日期。

关于ios - 每天和每半小时重复一次 UNNotifications,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45116819/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com