切换以在 swiftui 中获得通知

toggle to get notified in 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)
                    }
                }
                
                
            }
             
        }
    }
}

我创建了一个 func,当切换为 true 时,func 将执行,但当它为 false 时,则不会。但是,当我创建一个 if 语句时,出现错误

Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols

谁能解释一下我做错了什么?

你不能这样调用函数。 var body: some View { 中的所有内容都必须是 View,而 noonNotify() 不 return 是 View

相反,添加一个 onChange 块,每当 noon 更改时都会触发该块。

Toggle(isOn: $noon) {
    Text("ThirdHour")
}
.onChange(of: noon) { newValue in
    if newValue {
        noonNotify()
    }
}