如何在 SwiftUI 中使用切换开关打开和关闭通知

How can I turn notifications on and off with toggle in SwiftUI

变量

@State var notificationsOn: Bool = false

函数

func pushEnabledAtOSLevel(){

    UNUserNotificationCenter.current().getNotificationSettings { (settings) in
                  if settings.authorizationStatus == .denied {
                      // Notifications are allowed
                      let content = UNMutableNotificationContent()
                      content.title = "Elini Yıka"
                      content.subtitle = "Çabuk ol git! Elini Yıka!"
                      content.sound = UNNotificationSound.default

                      // show this notification five seconds from now
                      let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false)

                      // choose a random identifier
                      let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)

                      // add our notification request
                      UNUserNotificationCenter.current().add(request)
                      //self.notificationsOn = true

                  }
                  else {
                      UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
                          if success {
                            //MARK: - Toogle'ın değiştiği yer.
                              print("Bildirimlere izin verildi.")
                            //Toggle'ıdeğiştirdiğim yer burası.

                              self.notificationsOn = true
                          } else if let error = error {
                              print("Bildirimler kapalı.")
                              print(error.localizedDescription)
                            //Toggle'ıdeğiştirdiğim yer burası.
                              self.notificationsOn = false
                          }
                      }
                  }
              }
          }

切换

Toggle(isOn: $notificationsOn) {
                    Text("Bildirimler")
                        .font(.system(size: 17, design: .rounded))
                }

我尝试用 willset 和 didset 触发变量,但没有成功。 当我关闭切换时,通知将关闭。当我打开 Toggle 时,它​​会请求许可并打开通知。我做不到。

像这样使用获取和设置:

@State var notificationsOn = false

var body: some View {

    let toggle = Binding<Bool> (
        get: { self.notificationsOn },
        set: { newValue in
            self.notificationsOn = newValue
            // Do more stuff here.
            }
    })

在你的 Toggle 中:

Toggle(isOn: toggle) {Text("Activate") }