In the app, the user is supposed to watch a setup video. If they don't finish watching and click the 'close' button, I want to know where they stopped so I can have the video start at that spot once they start watching again.
I want to know what the time is that they stopped watching so I can save that number to the server for later use, using the following code:
player.seek(to: CMTimeMakeWithSeconds(637, 1))
I tried the following:
func showUnplayedVideo() {
// 1. check to see if user has already watched the app overview video
ref.child("videos")
.child("appOverview")
.child("watched")
.observeSingleEvent(of: .value) { (snapshot) in
let watched = snapshot.value as? Bool ?? false
if !watched {
// 2. show setup video popup on first load
guard let videoURL = URL(string: VideoURL.appOverview.rawValue) else { print("url error"); return }
let player = AVPlayer(url: videoURL)
self.playerVC.player = player
// 3. dismiss the player once the video is over and update Firebase
NotificationCenter.default.addObserver(self,
selector: #selector(self.playerDidFinishPlaying),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: self.playerVC.player?.currentItem)
NotificationCenter.default.addObserver(self,
selector: #selector(self.playerWasStoppedPrematurely),
name: NSNotification.Name.AVPlayerItemFailedToPlayToEndTime,
object: self.playerVC.player?.currentItem)
self.present(self.playerVC, animated: true) {
self.playerVC.player?.play()
}
}
}
}
@objc func playerWasStoppedPrematurely(note: NSNotification) {
self.playerVC.dismiss(animated: true)
print(playerVC.player?.currentTime())
}
The first notification 'AVPlayerItemDidPlayToEndTime' works great (for users who watch the video all the way through), but my other notification 'AVPlayerItemFailedToPayToEndTime' doesn't work (for users who stop part way through the video).
How do I get the stopping point of my users if they don't watch the whole video?
EDIT #1
This is what the screen looks like when the video is playing:
You are presenting the playerVC from a view controller. When the playerVC dismisses, viewDidAppear()
in your view controller will be called. This is a choice to put the time checking code.
Original Answer
You are already using player.currentTime()
. Why not also put it in the close button handler? Something like this
let current = Double(CMTimeGetSeconds(avPlayer.currentTime()))