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

在 SwiftUI 中切换通知

如何解决在 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 举报,一经查实,本站将立刻删除。