首页 文章

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

提问于
浏览
2

Scenario :我有一个 tableView 有很多单元格 . 每个单元格都包含一个AVPlayer来播放视频 . 一旦用户按下单元格上的播放按钮,就会创建AVPlayer . 我希望AVPlayer停止播放它的视频,并在它移动到屏幕外时移除它 .

The Issue :当单元格在屏幕外移动时,媒体仍将播放 . 因此,当我尝试删除我需要的播放器时,我的应用程序崩溃并出现错误

由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因是:'AVPlayer实例无法删除由另一个AVPlayer实例添加的时间观察者 .


How the player is being created

(在单元格中)

-(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];
    }

}

How the addTimeObserver is being added

-(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];
        }
    }];
}

How the player is being removed

(在UITableViewController中)

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

    [cell breakDownPlayer];
}

(在单元格中)

-(void)breakDownPlayer {

    [self.player breakDown];
}

(在玩家子类中)

-(void)breakDown {

    [self.player removeTimeObserver:self.observerToken];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
}

Question :如果 didEndDisplayingCell 被调用且应用程序没有崩溃,如何从 UITableViewCell 删除播放器?

1 回答

  • 3

    您是否尝试在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;
      }  
    }
    

相关问题