iosapplication-settingsviewwillappearviewwilldisappearviewcontroller-lifecyle

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


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.


Solution

  • 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")
        }
    }