Search code examples
notificationsswiftuitoggleuilocalnotificationunusernotificationcenter

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


Variable

@State var notificationsOn: Bool = false

Function

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

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

I tried triggering the variable with willset and didset but it didn't. The notification will turn off when I close toggle. When I open Toggle, it will ask for permission and will open the notifications. I couldn't do that.


Solution

  • Use get and set like this:

    @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.
                }
        })
    

    And in your Toggle:

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