3

Hi guys I am having a problem with UIPageViewController and Notifications.

I have a page UIPageVewController with a array of pages, so in these pages I have a AVplayer playing in loop as bellow:

 func loopVideo(videoPlayer:AVPlayer){
    NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil, queue: nil){
        [weak videoPlayer] notification in
        videoPlayer?.seek(to: kCMTimeZero)
        videoPlayer?.play()
    }
}

The problem is when I change page with scroll the notifications from another pages change my current video playing AVPlayer. I put a print inside the notification and I can see calling the other pages notifications. I don't Know what I have to do?

I tried remove the notification in the viewDidDisappear using NotificationCenter.default.removeObserver(self) but didn't work.

Can you help me?

Thanks

Allan Braga
  • 460
  • 5
  • 19

2 Answers2

11

NotificationCenter.default.removeObserver(self) won't work here as you never added yourself as a target.

Instead keep a reference to your notification and remove it. I think it should look something like this:

var notificationObserver:NSObjectProtocol?

func loopVideo(videoPlayer:AVPlayer){
    self.notificationObserver = NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil, queue: nil){
        [weak videoPlayer] notification in
        videoPlayer?.seek(to: kCMTimeZero)
        videoPlayer?.play()
    }
}

func removeObserver() {
    NotificationCenter.default.removeObserver(self.notificationObserver)
}
James P
  • 4,786
  • 2
  • 35
  • 52
  • I understood James P thanks for your answer I can understand better now. I resolved the with the answer from @Sneak. – Allan Braga Feb 15 '17 at 17:51
2

You can simply do a check when your notification is received.

Check if the notification object as AVPlayerItem is the same as the visible views player playerItem, videoPlayer.currentItem

Or simply check if the AVPlayerItem in the notification is the same as the yourCustomView.playerItem

EDIT:

I see your object is nil, it should be the AVPlayerItem. Check this thread.

Community
  • 1
  • 1
  • 1
    Thanks Sneak as do you said I resolved the problem inserting the player.currentItem. Thanks very much my dear! – Allan Braga Feb 15 '17 at 17:21