首页 > 解决方案 > 在 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)
                
            }
            
        }
    }
}

标签: iosswiftuixcode12

解决方案


推荐阅读