View will appear is not firing when we dismiss notification settings overlay

374 Views Asked by At

I have a view controller when a button clicked I'm taking the user to app settings.

 UIApplication.openApplicationSettings()

When I come back from appsettings to app then viewwillappear method is not firing.

or is there any other method that will let us know the appsettings is dismissed and user is seeing the screen right now.

2

There are 2 best solutions below

10
On BEST ANSWER

You should be using app lifecycle events (SceneDelegate/AppDelegate), not view controller lifecycle events (viewDidLoad, viewDidAppear, etc). sceneDidBecomeActive(_:) should be fine for your purposes — for iOS 13+, you should be using SceneDelegate to listen to scene phases, like going to settings (becoming inactive) and then coming back (becoming active again).

/// SceneDelegate.swift
func sceneDidBecomeActive(_ scene: UIScene) {
    // Called when the scene has moved from an inactive state to an active state.
    // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.

    /// your code here
}

If you want to listen to sceneDidBecomeActive directly in your view controller, try listening to the didActivateNotification notification.

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver( /// add observer
            self,
            selector: #selector(activated),
            name: UIScene.didActivateNotification,
            object: nil
        )
    }
    
    @objc func activated() {
        print("View controller is back now")
    }
}
5
On

Subscribe to following appdelegate events

applicationDidBecomeActive 

or

applicationWillEnterForeground

In ViewDidLoad use below code snippet

NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)

and use below method

  @objc func applicationDidBecomeActive(notification: NSNotification) {
        updateTableUI()
    }

Remove observer

   deinit {
           NSNotificationCenter.defaultCenter().removeObserver(self)
   }