2017-02-28 64 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方法的調用。我發現通知最適用於時間不太緊急的情況。