iOS NSNotificationCenter to check whether the app came from background to foreground

前端 未结 7 969
我在风中等你
我在风中等你 2020-12-07 00:41

I have a situation in which i have to intialize an object everytime when it comes from background to foreground and that should be using the NSNotificationCenter not with ap

7条回答
  •  爱一瞬间的悲伤
    2020-12-07 01:06

    Swift 5

    Subscribe to Notification -

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    
        NotificationCenter.default.addObserver(
          self,
          selector: #selector(applicationWillEnterForeground(_:)),
          name: UIApplication.willEnterForegroundNotification,
          object: nil)
    }
    

    Remove subscription -

    override func viewWillDisappear(_ animated: Bool) {
            super.viewWillDisappear(animated)
    
            NotificationCenter.default.removeObserver(self)
    } 
    

    Function to be called -

    @objc func applicationWillEnterForeground(_ notification: NSNotification) {
           self.volumeSlider.value = AVAudioSession.sharedInstance().outputVolume
        }
    

提交回复
热议问题