Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...