【问题标题】:How to stop AVPlayer playback in cell when the cell has moved offscreen当单元格移出屏幕时如何在单元格中停止 AVPlayer 播放
【发布时间】:2015-11-16 21:06:25
【问题描述】:

场景:我有一个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];
    }

}

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

玩家是如何被移除的

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

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

【问题讨论】:

    标签: ios objective-c uitableview avplayer


    【解决方案1】:

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

    【讨论】:

    • 我应该知道...谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-26
    • 1970-01-01
    • 2020-08-13
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多