切换以在 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 语句时,出现错误

类型'()'不能符合'View';只有 struct/enum/class 类型才能符合协议

有人可以解释我做错了什么吗?

解决方法

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

相反,添加一个 onChange 块,它会在 noon 更改时触发。

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