在 SwiftUI 中切换通知

问题描述

我希望我的应用的用户可以打开或关闭他们是否希望在中午收到通知。我设法让它在某种程度上起作用,但我遇到了一些问题。

  1. 有时会触发通知,有时则不会
  2. 通知可通过按钮使用,但不适用于切换。

我尝试寻找解决方案,但没有成功。如果有人可以提供帮助,那就太好了。

struct Alert: View {
    @State var noon = false
    var body: some View {
        
        vstack {
            
            Toggle(isOn: $noon) {
                Text("noon")
            }
            
            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)
                    }
                }
                
            }
            
            Button("Schedule Notification") {
                
                
                let content = UNMutableNotificationContent()
                content.title = "Meds"
                content.subtitle = "Take your meds"
                content.sound = UNNotificationSound.default
                
                
                var dateComponents = DateComponents()
                dateComponents.hour = 12
                let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents,repeats: false)
                
                // choose a random identifier
                let request = UNNotificationRequest(identifier: UUID().uuidString,content: content,trigger: trigger)
                
                // add our notification request
                UNUserNotificationCenter.current().add(request)
                
            }
            
        }
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)