在observeValueForKeyPath中发送NSNotification

时间:2017-02-28 00:08:39

标签: ios avplayer key-value-observing kvocontroller

我有AVPlayer的费率观察员。

[self.player addObserver:self
                          forKeyPath:@"rate"
                             options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew
                             context:&RateContext];

在我的observeValueForKeyPath方法中,我正在尝试发送通知让playerLayer superView知道播放器何时启动/停止。

- (void)observeValueForKeyPath:(NSString *)keyPath
                  ofObject:(id)object
                    change:(NSDictionary<NSString *,id> *)change
                   context:(void *)context {

    if ([keyPath isEqualToString:@"rate"]) {
        if (self.player.rate == 0) {
            [self.indicatorView startAnimating];
            dispatch_async(dispatch_get_main_queue(), ^{
                 [[NSNotificationCenter defaultCenter] postNotificationName:@"playerStopped" object:nil];
             });
            [self videoStalled];
        }else if (self.player.rate == 1){
            [self.indicatorView stopAnimating];
          //dispatch_async(dispatch_get_main_queue(), ^{
          //   [[NSNotificationCenter defaultCenter] postNotificationName:@"playerStarted" object:nil userInfo:dic];
          //});
        }
        return;
    }

在我的videoStalled我等到视频的更多内容已加载,然后致电[self.player play]。然后调用“速率”,只有在我注释掉通知帖后,视频才会立即播放。当我取消注释通知时,仍然会调用“Rate”,但玩家在几秒钟后才会播放。不知道大滞后的来源。

1 个答案:

答案 0 :(得分:0)

使用一些NSLog调用来显示流程的去向以及花费的时间。

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSString *,id> *)change
                       context:(void *)context {

    if ([keyPath isEqualToString:@"rate"]) {
        if (self.player.rate == 0) {
            [self.indicatorView startAnimating];
            [self videoStalled];
            NSLog(@"stage 1");
            [[NSNotificationCenter defaultCenter] postNotificationName:@"playerStopped" object:nil];
        }else if (self.player.rate == 1){
            [self.indicatorView stopAnimating];
            //dispatch_async(dispatch_get_main_queue(), ^{
            //   [[NSNotificationCenter defaultCenter] postNotificationName:@"playerStarted" object:nil userInfo:dic];
            //});
        }
        return;
    }
}

- (void) playerStopped
{
    NSLog(@"stage 2");
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"stage 3");
        [self.player play];
    });
}

通过这种方式,您将看到它是否是一个减慢速度的线程。您也可以使用另一个观察者而不是通知来触发对playStopped方法的调用。我发现通知最适合在时间紧迫的情况下使用。