ios – 如何替换MPMoviePlayer通知?

前端之家收集整理的这篇文章主要介绍了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的大部分(如果不是全部)通知

原文链接:https://www.f2er.com/iOS/328810.html

猜你在找的iOS相关文章