现在我该如何替换这些通知呢?
AVPlayerViewController
与MPMoviePlayerViewController
在使用上有很大的区别。你需要使用Key Value Observing来确定与AVPlayerViewController
相关联的AVPlayer
对象的当前特性,而不是使用通知。根据文档:
您可以使用键值观察来观察播放器的状态。因此,您可以安全地添加和删除观察者,AVPlayer会将动态发生的更改通知序列化到调度队列中进行处理。默认情况下,此队列为主队列(请参见dispatch_get_main_queue)。为了确保在可能报告播放状态中的动态更改时安全访问播放器的非原子属性,您必须使用接收方的通知队列对访问进行序列化。在常见情况下,通过在主线程或队列上调用AVPlayer的各种方法自然地实现这种序列化。
例如,如果您想知道何时暂停播放器,请在AVPlayer
对象的rate
属性上添加观察者:
[self.player addObserver:self forKeyPath:@"rate" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context: &PlayerRateContext];
然后在观察方法中检查new
值是否等于零:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
if (context == &PlayerRateContext) {
if ([[change valueForKey:@"new"] integerValue] == 0) {
// summon Sauron here (or whatever you want to do)
}
return;
}
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
return;
}
AVPlayer
的属性是可以被观察的。请参阅类参考。
此外,除了这些属性之外,还有一些针对AVPlayerItem
对象的通知可用,虽然数量有限但仍然很有帮助。
通知
AVPlayerItemDidPlayToEndTimeNotification
AVPlayerItemFailedToPlayToEndTimeNotification
AVPlayerItemTimeJumpedNotification
AVPlayerItemPlaybackStalledNotification
AVPlayerItemNewAccessLogEntryNotification
AVPlayerItemNewErrorLogEntryNotification
我特别喜欢使用AVPlayerItemDidPlayToEndTimeNotification
,一旦播放结束就将项目定位到开头。
将这两个选项结合使用,您应该能够替换大多数(如果不是全部)MPMoviePlayerController
的通知。
MPMoviePlayerNotifications
和AVPlayerItemNotifications
的文档,发现两件事情。
MPMoviePlayerNotifications
没有显示它们已被弃用:
AVPlayerItemNotifications
没有任何可见的替代品:
所以,我有些困惑,因为你说MPMoviePlayerNotifications
已经被弃用了,但文档上说它们仍然可用。另外,我认为AVPlayerItemNotifications
没有替代MPMoviePlayerNotifications
。
MPMoviePlayerViewController类在iOS 9中正式弃用。(MPMoviePlayerController类也被正式弃用。)为了在iOS 9及更高版本中播放视频内容,应该使用AVKit框架中的AVPictureInPictureController或AVPlayerViewController类,或者使用WebKit中的WKWebView类。
我猜这意味着未来不会有MPMoviePlayerNotifications
通知。 - Roman Truba