【发布时间】:2022-01-19 21:43:37
【问题描述】:
我的问题是我正在尝试安排每天在特定时间发送的通知,这是我的代码
import SwiftUI
struct notifView: View {
var body: some View {
VStack {
VStack {
Button("Request Permission") {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
print("Access Granted!")
} else {
print("Access Not Granted")
}
}
}
.frame(width: 200, height: 60, alignment: .center)
.foregroundColor(.black)
.background(Color.blue)
.cornerRadius(10.0)
.padding()
Button("Add Notifications For Morning") {
func scheduleNotification() {
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "Morning Time"
content.body = "Wake Up And Be Productive!"
content.categoryIdentifier = "reminder"
content.sound = UNNotificationSound.default
var dateComponents = DateComponents()
dateComponents.hour = 6
dateComponents.minute = 30
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
center.add(request)
}
}
.padding()
Button("Add Notifications For Middle Of The Day") {
func scheduleNotification() {
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "Middle Of The Day"
content.body = "Did you have your daily run?"
content.categoryIdentifier = "reminder"
content.sound = UNNotificationSound.default
var dateComponents = DateComponents()
dateComponents.hour = 12
dateComponents.minute = 30
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
center.add(request)
}
}
.padding()
Button("Add Notifications For Night") {
func scheduleNotification() {
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "Night Time"
content.body = "Time to sleep"
content.categoryIdentifier = "reminder"
content.sound = UNNotificationSound.default
var dateComponents = DateComponents()
dateComponents.hour = 20
dateComponents.minute = 51
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
center.add(request)
}
}
.foregroundColor(.blue)
.padding()
}
}
}
}
struct notifView_Previews: PreviewProvider {
static var previews: some View {
notifView()
}
}
【问题讨论】:
-
@loremipsum 我想每天重复一次,而不是每 x 天
-
那么,x = 1?这些链接更多地是关于通知的设置。您缺少关键部分,例如委托和告诉您的应用如何处理通知,请查看两个链接。
-
如果我的代码回答了您的问题,请接受并可能支持