ios – 如何替换MPMoviePlayer通知?

在iOS 9中,MPMoviePlayer和他的所有组件都已弃用.
我们使用MPMoviePlayerController通知,如MPMoviePlayerLoadStateDidChangeNotification,MPMovieDurationAvailableNotification,MPMoviePlayerPlaybackStateDidChangeNotification,MPMoviePlayerReadyFordisplayDidChangeNotification,来跟踪视频服务质量.但是现在使用AVPlayerViewController我找不到这些通知的正确替换.

如何立即替换这些通知

解决方法

AVPlayerViewController与MPMoviePlayerViewController的用法有很大不同.您可以使用Key Value Observing来确定与AVPlayerViewController关联的AVPlayer对象的当前特征,而不是使用通知.根据文件

You can observe the status of a player using key-value observing. So
that you can add and remove observers safely,AVPlayer serializes
notifications of changes that occur dynamically during playback on a
dispatch queue. By default,this queue is the main queue (see
dispatch_get_main_queue). To ensure safe access to a player’s
nonatomic properties while dynamic changes in playback state may be
reported,you must serialize access with the receiver’s notification
queue. In the common case,such serialization is naturally achieved by
invoking AVPlayer’s varIoUs methods on the main thread or queue.

例如,如果您想知道播放器暂停的时间,请在AVPlayer对象的rate属性添加一个观察者:

[self.player addobserver:self forKeyPath:@"rate" options:NSkeyvalueObservingOptionNew | NSkeyvalueObservingOptionOld context: &PlayerRateContext];

然后在observe方法中检查新值是否等于零:

- (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上的许多属性都是可观察的.通过Class reference.

除此之外,还有几个可用于AVPlayerItem对象的通知,这些通知有限但仍然有用.

Notifications

AVPlayerItemDidplayToEndTimeNotification

AVPlayerItemFailedToPlayToEndTimeNotification

AVPlayerItemTimeJumpednotification

AVPlayerItemPlaybackStallednotification

AVPlayerItemNewAccessLogEntryNotification

AVPlayerItemNewErrorLogEntryNotification

我发现AVPlayerItemDidplayToEndTimeNotification对于在播放完成后将项目设置为开始特别有用.

一起使用这两个选项,您应该能够替换MPMoviePlayerController的大部分(如果不是全部)通知

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...