Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

ios - How to detect if notification is turn on when the app comes back from Settings in Swift 5?

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.

  1. App is launch, user click on toggle switch (Notification request dialogue will pop up).
  2. If user decline the initial request and click on toggle switch again, a dialogue will pop up and suggest/bring the user to the app's settings. (the app goes to background, Settings is front)
  3. when the user turn on the Notification Settings, then go back to the app (Settings goes to background, the app comes to foreground).

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
     }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...