9

我正在使用 AVPlayer 从 url 播放视频。 AVPlayerItemDidPlayToEndTimeNotification没有触发。我已经设置了断点来检查。以下是我的代码片段:-

    @IBAction func playButtonClicked(sender: UIButton) {
    let url:NSURL = NSURL(string: self.currentSelectedContent.link)!
    moviePlayer = AVPlayer(URL: url)
    playerViewController = AVPlayerViewController()
    playerViewController.player = moviePlayer

    self.presentViewController(playerViewController, animated: true) {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "moviePlayBackFinished", name: AVPlayerItemDidPlayToEndTimeNotification, object: self.moviePlayer)
        self.playerViewController.player?.play()
    }

}

func moviePlayBackFinished() {
    self.playerViewController.dismissViewControllerAnimated(true, completion: nil)
}
4

3 回答 3

21

根据文档,观察到的对象必须是AVPlayerItem实例,而不是AVPlayer本身。尝试更改self.moviePlayerself.moviePlayer.currentItem.

于 2016-03-25T03:10:04.453 回答
5

AVPlayer 的 actionAtItemEnd 属性符合 KVO:

moviePlayer.addObserver(self, forKeyPath: "actionAtItemEnd", options: [], context: nil)


override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    if keyPath == "actionAtItemEnd"{
        // 
        print("FINISH")
    }
}

https://developer.apple.com/documentation/avfoundation/avplayer/1387376-actionatitemend

https://developer.apple.com/documentation/avfoundation/avplayeractionatitemend

于 2015-11-23T12:37:59.453 回答
4

这对我有用:

NotificationCenter.default.addObserver(self, 
selector:#selector(didEndPlayback), 
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object:nil)
于 2017-02-07T18:22:58.653 回答