gpt4 book ai didi

ios - 如何安排一周中特定两天的本地通知?

转载 作者:行者123 更新时间:2023-11-28 07:22:05 25 4
gpt4 key购买 nike

我想安排每周触发两次通知:

let gregorian = Calendar(identifier: .gregorian)
let now = Date()

[2, 4].forEach { day in
let content = UNMutableNotificationContent()
content.title = "Notif title"
content.body = "Comment"
content.sound = .default
var components = gregorian.dateComponents([.year, .month, .weekdayOrdinal, .day, .hour, .minute, .second], from: now)
components.hour = 11
components.minute = 25
components.second = 0
components.weekdayOrdinal = day

let date = gregorian.date(from: components)!
let triggerDaily = gregorian.dateComponents([.weekdayOrdinal, .hour, .minute, .second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
let request = UNNotificationRequest(identifier: "test", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Oops: \(error)")
} else {
print("Notification created!")
}
}
}

但是它不是在星期一和星期三被解雇一次,而是每天被调用两次。

我做错了什么?感谢您的帮助。

最佳答案

由于 foreach 循环,您的代码会安排两个具有相同标识符的通知。当您的代码正在执行第二个循环时覆盖请求。

我进行了一些研发并稍微改进了您的代码。在我这边,它工作得很好。

请尝试下面提到的代码。

func setNotification() {
let days = [2,4]

func ScheduleNotification(index:Int){
let calendarComponents = NSDateComponents()
calendarComponents.hour = 11
calendarComponents.minute = 25
calendarComponents.second = 0
calendarComponents.weekday = days[index]

let content = UNMutableNotificationContent()
content.title = "Notification title"
content.body = "your message here."
content.sound = UNNotificationSound.default

let trigger = UNCalendarNotificationTrigger(dateMatching: calendarComponents as DateComponents, repeats: true)
let identifier = "UYLLocalNotification\(days[index])"
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)

UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error) in
if let error = error {
print(error)
}else{
if index == 0{
ScheduleNotification(index: 1)
}
}
})
}
ScheduleNotification(index: 0)
}

在您的 viewdidLoad 方法中调用此函数。

self.setNotification()

我希望它能节省您的时间。

关于ios - 如何安排一周中特定两天的本地通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57754428/

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