2017-02-28 25 views
0

我有一个速度观察者AVPlayer发送NSNotification在observeValueForKeyPath

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

在我observeValueForKeyPath方法,我试图发送一个通知,让playerLayer上海华知道,当玩家已经开始/停止。

- (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]。然后调用“费率”,视频将立即播放,只要我注释掉通知帖子即可。当我取消通知,“价格”仍然是所谓但是玩家不玩了,直到几秒钟后。不确定那里的滞后来自何处。

+0

滞后是从分派到你正在做的主UI线程。您不需要实际派发到UI线程来发布通知。另外,如果你是不是在主(UI)线程,调用'[self.indicatorView stopAnimating]'应该崩溃的应用程序 – Lefteris

回答

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方法的调用。我发现通知最适用于时间不太紧急的情况。

相关问题