How to tell the active view controller when applicationDidBecomeActive is called?

后端 未结 6 1295
孤独总比滥情好
孤独总比滥情好 2021-02-02 12:01

I feel I am missing a trick here...

I just want to call viewDidLoad or viewDidAppear on the current active view controller when applicationDidBecomeActive gets called, s

6条回答
  •  灰色年华
    2021-02-02 12:42

    Ok so it's pretty catastrophic.

    You guys have to pay attention to events registration/unregistration cause you can cause memory leaks.

    To make everything work you need to set a flag which knows what's the registration status: either you signed to background events or not. Notice that you need to register to the events when the view controller is seen by the user (if he came from a different one) or if he came from the home screen to your view controller.

    You also need to unregister when you leave the view controller to a different one.

    In short:

    Swift 4:

    private var registeredToBackgroundEvents = false
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        registerToBackFromBackground()
    }
    
    /// register to back from backround event
    private func registerToBackFromBackground() {
        if(!registeredToBackgroundEvents) {
            NotificationCenter.default.addObserver(self, 
            selector: #selector(viewDidBecomeActive), 
            name: UIApplication.didBecomeActiveNotification, object: nil)
            registeredToBackgroundEvents = true
        }
    }
    
    /// unregister from back from backround event
    private func unregisterFromBackFromBackground() {
        if(registeredToBackgroundEvents) {
            NotificationCenter.default.removeObserver(self, 
            name: UIApplication.didBecomeActiveNotification, object: nil)
            registeredToBackgroundEvents = false
        }
    
    }
    
    @objc func viewDidBecomeActive(){
        logicManager.onBackFromStandby()
    }
    
    
    override func viewWillDisappear(_ animated: Bool) {
        unregisterFromBackFromBackground()
    }
    

提交回复
热议问题