Katherine Jenkins Katherine Jenkins - 2 years ago 189
Swift Question

Adding & Removing NSNotificationCenter Observer - UIApplicationDidEnterBackgroundNotification - The Correct Way?

I have a UIView that plays audio, has a NSTimer and progress circular bar animation.

To keep things simple, if the user switches apps or takes a call, I would like all processes to stop and reset themselves.

I propose to use:

  1. Call the Observer - perhaps in

    override func viewWillAppear(animated: Bool) {

    // set observer for WillEnterForeground
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(WorkoutFullFace1Exercise7TVC.willEnterBackground), name: UIApplicationDidEnterBackgroundNotification, object: nil)



  1. Stop relevant tasks:

    // Stop all audio, timer and animation if app enters background.
    func willEnterBackground() {

    myAudioPlayer.currentTime = 0

    swiftCounter = 60
    timerLabel.text = String(swiftCounter)

    pauseBtn.alpha = 1.0

    playBtn.alpha = 1.0

    stopBtn.alpha = 1.0

    currentCount = 0
    circularProgressView.animateFromAngle(circularProgressView.angle, toAngle: 0, duration: 0.5, completion: nil)

  2. Dismiss the observer:

    override func viewWillDisappear(animated: Bool) {

    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidEnterBackgroundNotification, object: nil)

    .... }

Where is the correct place to load and dismiss the observer? I have read threads that state to use
viewWillAppear / Disappear
, etc..

Can anyone please shed some light on what is recommended for my scenario and also what is current and likely to remain 'usable' in the future (language and practise seems to change rapidly in the programming World).

And am I using the correct syntax above?


Answer Source

Everything seems correct to me

Just make sure to call super implementation in each method. That can lead to some issues when you are subclassing things later

 override func viewWillAppear(animated: Bool) {
      // other code

 // same for viewWillDisappear
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download