Xcode 切换以在swiftui中获得通知

Xcode 切换以在swiftui中获得通知,xcode,swiftui,xcode12,Xcode,Swiftui,Xcode12,我希望能够在每天的特定时间通知我的应用程序的用户。在本例中,时间是中午 import SwiftUI import UserNotifications struct Alert: View { @State var noon = false func noonNotify() { let content = UNMutableNotificationContent() content.title =

我希望能够在每天的特定时间通知我的应用程序的用户。在本例中,时间是中午

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语句时,我得到了一个错误

类型“()”不能与“视图”一致;只有结构/枚举/类类型才能符合协议


有人能解释一下我做错了什么吗?

你不能调用那样的函数。
var主体内的所有内容:某些视图{
必须是
视图
,并且
nonotify()
不返回
视图

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

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

我在我的资产中添加了一个mp3声音,并希望将其用作我的通知声音。我将其添加到代码中,但它不起作用,它只是发出默认声音``content.sound=UNNotificationSoundName(名称:UNNotificationSoundName(rawValue:“notifysound.mp3”))“``你会碰巧知道怎么做吗?@CodeBeast我从来没有使用过通知。但你应该把它作为一个新问题发布