微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

切换以在 swiftui 中获得通知

如何解决切换以在 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()
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。