I have a switch button that will trigger notification alerts. I was able to implement asking for Notification permission (first time the user trigger the switch), I was also able to implement bringing the user to open the app's notification settings when the user click on the switch button again (if the user decline the first request). But I am having problem on how to get that Notification is turn on information back to the app.
At this stage, how can I detect Notification setting for the app is turn on and show the switch button as 'on'?
I tried override func viewWillAppear (this doesn't work because the viewcontroller never calls/reload again when you go back to the app from Settings.) I also tried in AppDelegate, applicationWillEnterForeground and applicationDidBecomeActive, both didn't work either.
I hope this make sense. Thank you for any suggestion.
Import UserNotifications into your ViewController
import UserNotifications
Create a method to check the current notification status
private func hasNotificationPermission(completion: @escaping (Bool) -> Void) {
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
completion(settings.authorizationStatus == .authorized)
}
}
Add observer to detect when app becomes active
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(self.openactivity), name: NSNotification.UIApplicationDidBecomeActive, object: nil)
}
When coming back from background check for Notification status and update your UI
@objc func appBecomeActive() {
if hasNotificationPermission {
// Notifications are enabled
} else {
// Notifications are not enabled
}
}