bruno617
bruno617

Reputation: 60

How can I check if a specific type of local notification is enabled?

If I request authorization for local notifications for alerts and sounds using the code below, the user could go into settings after granting authorization turn off banners and sounds. Authorization would still exist, but there would be no methods for sending notifications. How can I check if specific types of notifications (e.g. alert) is enabled?

@objc func registerLocal() {
    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
        if granted {
            self.notificationsAuth = true
        } else {
            self.notificationsAuth = false
        }
        self.notificationAuthUndertermined = false
    }
}

Upvotes: 0

Views: 464

Answers (2)

Mahsa Yousefi
Mahsa Yousefi

Reputation: 236

For iOS 10.0 and later:

UNUserNotificationCenter.current().getNotificationSettings { (settings) in

        // also available for badgeSetting, soundSetting, authorization status and ...

        switch settings.alertSetting {
        case .notSupported:
            // Do stuff
            break

        case .disabled:
            // Do stuff
            break

        case .enabled:
            // Do stuff
            break
        }
}

Upvotes: 2

We can verify alertSetting, soundSetting, badgeSetting is enabled or not using below code,

 func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { settings in
    print("Notification settings: \(settings)")

    let isAlertEnabled = settings.alertSetting
    let isSoundEnable = settings.soundSetting
    let isbadgeEnabled = settings.badgeSetting

    if(isAlertEnabled == .enabled && isSoundEnable == .enabled && isbadgeEnabled == .enabled){
      print("Alert, Sound and Badges are enabled.")
    }else{
        //Different action
    }
  }
}

Upvotes: 0

Related Questions