gpt4 book ai didi

swift3 - 每周触发通知 Swift 3

转载 作者:行者123 更新时间:2023-11-30 11:03:26 25 4
gpt4 key购买 nike

我正在尝试制定一个时间表,其中我需要记住我类的所有几周,例如星期一的某个时间。问题是,如果我在打印变量triggerWeekly时指定weekday = 1(星期日),它会告诉我weekday = 2,因此通过执行测试我不会收到此类通知。我需要知道为什么会发生这种情况

let weekday = 1 //Sunday 19 Mar 
let calendar = NSCalendar.current
var date = DateComponents()
date.weekday = weekday
date.hour = 1
date.minute = 5

let ultimateDate = calendar.date(from: date)

let triggerWeekly = Calendar.current.dateComponents([.weekday, .hour, .minute], from:
ultimateDate!)

print(triggerWeekly) // hour: 1 minute: 5 second: 0 weekday: 2 isLeapMonth: false
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)
let identifier = "curso\(String(Index))"
let request = UNNotificationRequest(identifier: identifier,
content: content, trigger: trigger)

最佳答案

您可以将触发器设置为每周一凌晨 1:05 重复,如下所示:

import UserNotifications

let trigger = UNCalendarNotificationTrigger(dateMatching: DateComponents(hour: 1, minute: 5, weekday: 2), repeats: true)
print(trigger.nextTriggerDate() ?? "nil")

let content = UNMutableNotificationContent()
content.title = "title"
content.body = "body"
// make sure you give each request a unique identifier. (nextTriggerDate description)
let request = UNNotificationRequest(identifier: "identify", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print(error)
return
}
print("scheduled")
}

在尝试安排通知之前,不要忘记询问用户是否允许安排通知:

UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]) { granted, error in
if granted {
print("authorized")
}
}

关于swift3 - 每周触发通知 Swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53022412/

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