0

My app is playing a video and I want to trigger an action when the video ends. The screen (A) is embedded in a navigation controller, and if I trigger a push (to B) and then come back (to A), the action (in A) still takes place based on the observer. There is also an option in my screen that triggers a modal (to C) which then gets dismissed to go back (to A). When I come back from the modal (C), however, the observer (in A) is gone.

Here's my code for screen A's view controller:

ScreenAViewController: UIViewController {
    override func viewDidLoad() {

        super.viewDidLoad()
        // Do more stuff

        NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.avPlayer.currentItem, queue: .main) { _ in
            // Do stuff
        }
    }
}

Here's the code that trigger the modal to screen C:

@IBAction func triggerModal(_ sender: UIButton) {
    avPlayer.pause()
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let screenCViewController = storyboard.instantiateViewController(withIdentifier: "ScreenC") as! ScreenCViewController
    present(screenCViewController, animated: true)
}

And finally here's the line that dismisses screen C:

dismiss(animated: true, completion: nil)
wizplum
  • 427
  • 5
  • 17

1 Answers1

0

addObserver returns an observer object. You are ignoring this and not retaining it. Therefore it goes out of scope and dies and the observation ends.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Imho that's not the case. Although it would definitely be better to keep a reference to the observer object for unregistering at a later point. – André Slotta Dec 25 '18 at 14:40
  • I think Matt is actually right. The observer isn't the object you pass in. It's actually a new object that's created and returned -- I might be mistaken but I'm pretty sure I read about this recently. This is a different addObserver method, it functions a bit differently. – Eman Harout Dec 25 '18 at 23:50
  • I added `var avPlayerObserver: NSObjectProtocol?` to the class properties and changed my code to have `avPlayerObserver = NotificationCenter.default.addObserver( // ...` but the observer still seems to be gone after coming back from the modal. Was this your suggestion or did I misunderstand? – wizplum Dec 28 '18 at 18:07
  • Well, maybe you need to tell us more about what “the observer still seems to be gone” means. Can you provide a clear reproducible example? – matt Dec 28 '18 at 18:29