在应用程序中,用户应该观看设置视频。如果他们没有看完并点击“关闭”按钮,我想知道他们在哪里停止,以便他们再次开始观看时我可以让视频从该位置开始。
我想知道他们停止观看的时间是几点,以便我可以使用以下代码将该号码保存到服务器以供以后使用:
player.seek(to: CMTimeMakeWithSeconds(637, 1))
我尝试了以下方法:
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())
}
第一个通知“AVPlayerItemDidPlayToEndTime”效果很好(对于从头到尾观看视频的用户),但我的另一个通知“AVPlayerItemFailedToPayToEndTime”不起作用(对于在视频中途停止的用户)。
如果用户没有观看整个视频,我如何获得他们的停止点?
编辑#1
这是视频播放时屏幕的样子:
最佳答案
您正在从 View Controller 呈现playerVC。当playerVC关闭时, View Controller 中的viewDidAppear()
将被调用。这是放置时间检查代码的选择。
原始答案
您已经在使用player.currentTime()
。为什么不把它也放在关闭按钮处理程序中呢?像这样的事情
let current = Double(CMTimeGetSeconds(avPlayer.currentTime()))
关于swift - 用户关闭AVPlayer时如何获取视频播放时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51738982/