当单元格移出屏幕时如何停止单元格中的 AVPlayer 播放

Bra*_*n A 3 objective-c uitableview ios avplayer

场景:我有tableView很多单元格。每个单元格将包含一个 AVPlayer 来播放视频。一旦用户按下单元格上的播放按钮,就会创建 AVPlayer。我希望 AVPlayer 停止播放它的视频并完全在它的单元格移出屏幕时删除。

问题:当单元格移出屏幕时,媒体仍将播放。因此,当我尝试根据需要删除播放器时,我的应用程序会因错误而崩溃

由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“AVPlayer 的实例无法删除由不同的 AVPlayer 实例添加的时间观察者。”


播放器是如何创建的

(在单元格中)

-(void)addPlayer {

    if (!self.player) {

        // This is my custom init method
        self.player = [[AVPlayer alloc] initWithFrame:self.container.bounds contentURL:mediaURL];
        [self.player setUserInteractionEnabled:YES];
        [self.container setUserInteractionEnabled:YES];
        [self.container addSubview:self.player];
    }

}
Run Code Online (Sandbox Code Playgroud)

如何添加 addTimeObserver

-(void)beginObservingTime {

// This will monitor the current time of the player

    __weak STPlayer *weakSelf = self;
    self.observerToken = [self.player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(1.0, NSEC_PER_SEC) queue:nil usingBlock:^ (CMTime time) {
        if (CMTimeGetSeconds(time) > self.playbackTime) {
            // done buffering
            [weakSelf updatePlaybackTime:CMTimeGetSeconds(time)];
            [weakSelf.player removeTimeObserver:weakSelf.observerToken];
            [weakSelf hideActivityIndicator];
        }
    }];
}
Run Code Online (Sandbox Code Playgroud)

玩家如何被移除

(在 UITableViewController 中)

-(void)tableView:(UITableView *)tableView didEndDisplayingCell:(FeedCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

    [cell breakDownPlayer];
}
Run Code Online (Sandbox Code Playgroud)

(在单元格中)

-(void)breakDownPlayer {

    [self.player breakDown];
}
Run Code Online (Sandbox Code Playgroud)

(在玩家子类中)

-(void)breakDown {

    [self.player removeTimeObserver:self.observerToken];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
}
Run Code Online (Sandbox Code Playgroud)

问题:如何从UITableViewCell一次didEndDisplayingCell调用中删除播放器并且应用程序不会崩溃?

小智 5

您是否尝试在 didEndDisplayingCell 方法中将播放器设置为 nil?

-(void)tableView:(UITableView *)tableView didEndDisplayingCell:(FeedCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
  if (cell.player.rate != 0 && (cell.player.error == nil)) {
    // player is playing
    cell.playButton.hidden = NO;
    cell.player = nil;
  }  
}
Run Code Online (Sandbox Code Playgroud)