xcode - 切换以在 swiftui 中获得通知
问题描述
我希望能够在每天的特定时间通知我的应用程序的用户。在这个例子中,时间是中午
import SwiftUI
import UserNotifications
struct Alert: View {
@State var noon = false
func noonNotify() {
let content = UNMutableNotificationContent()
content.title = "Meds"
content.subtitle = "Take your meds"
content.sound = UNNotificationSound.default
var dateComponents = DateComponents()
dateComponents.hour = 14
dateComponents.minute = 38
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
// choose a random identifier
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
// add our notification request
UNUserNotificationCenter.current().add(request)
}
var body: some View {
VStack {
Toggle(isOn: $noon) {
Text("ThirdHour")
}
if noon {
noonNotify()
}
Button("Request Permission") {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
if success {
print("All set!")
} else if let error = error {
print(error.localizedDescription)
}
}
}
}
}
}
我创建了一个函数,当切换为真时,函数将执行,但当它为假时,它不会。但是,当我创建 if 语句时,出现错误
类型 '()' 不能符合 'View';只有结构/枚举/类类型可以符合协议
有人可以解释我做错了什么吗?
解决方案
你不能调用这样的函数。里面的所有东西都var body: some View {
必须是 a View
,并且noonNotify()
不返回 a View
。
相反,添加一个块,每当更改onChange
时都会触发该块。noon
Toggle(isOn: $noon) {
Text("ThirdHour")
}
.onChange(of: noon) { newValue in
if newValue {
noonNotify()
}
}