播放video到UITableView

我已经阅读了几个关于直播video/audiopost。 不幸的是,似乎没有任何“好”的解决scheme。

我想为SDWebImageView提供的video提供相同的function。

现在,我正在使用以下代码: –

 NSURL *url=[[NSURL alloc] initWithString:@"http://www.ebookfrenzy.com/ios_book/movie/movie.mov"]; MPMoviePlayerController *moviePlayer=[[MPMoviePlayerController alloc] initWithContentURL:url]; moviePlayer.controlStyle=MPMovieControlStyleDefault; moviePlayer.shouldAutoplay=YES; 

但是当我滚动tableview ,所有的video一次又一次地下载 。 那么我怎样才能停止下载?

有没有更好的解决scheme播放video到UITableView ? 同样的Facebook,Instagram和Vine应用程序在做什么

不要使用MPMoviePlayerController ,使用AVFoundationAVPlayer

此外,不要将您的资产下载到您的UITableViewCell子类。 使用其他数据源下载和pipe理video资产。

有几种方法可以做到这一点。

  1. 保持由URL初始化的AVPlayerItem对象的数据源数组。 每次滚动到单元格时,不要每次加载资源,只需将AVPlayerItem加载到单元格的播放器中,并在滚动时将其删除。

  2. 如果您需要保留video数据,请考虑将每个video下载到Documents目录中的临时文件。 文件下载完成后,使用其initWithURL:方法将数据加载到AVAsset ,并将URL指向本地文件。 准备就绪后,可以使用initWithAsset:将资源加载到AVPlayerIteminitWithAsset:并播放video。

当你滚动表视图,然后方法-tableView:cellForRowAtIndexPath:被触发(实际上每当单元格将被视为此方法被调用时)。 我相信你是在这个方法中分配和初始化你的MediaPlayer,这就是为什么video再次下载。 你可以尝试添加数组并存储已经创build的单元格(某种caching)。 然后你的-tableView:cellForRowAtIndexPath应该检查它是否有caching的实际索引。 如果是,则显示caching的单元格。 如果没有,那么它应该创build单元格,分配和初始化播放器,然后将单元存储在caching中。

我的ViewController有属性: NSMutableDictionary *cache; 并在ViewDidLoad我有: cache = [[NSMutableDictionary alloc] init]; 我的-tableView:cellForRowAtIndexPath:看起来像这样:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellId = @"myCellId"; MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId]; if ([cache objectForKey:[NSString stringWithFormat:@"key%lu", indexPath.row]] != nil) { cell = [cache objectForKey:[NSString stringWithFormat:@"key%lu", indexPath.row]]; } else { NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MyTableViewCell" owner:self options:nil]; cell = [nib objectAtIndex:0]; AVPlayerViewController *playerViewController = [[AVPlayerViewController alloc] init]; playerViewController.player = [AVPlayer playerWithURL:[[NSURL alloc] initWithString:@"http://www.ebookfrenzy.com/ios_book/movie/movie.mov"]]; [cell addSubview:playerViewController.view]; [cache setValue:cell forKey:[NSString stringWithFormat:@"key%lu", indexPath.row]]; } return cell; } 

这个对我有用。 当然你需要使用自己的数据源等

Swift 3

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell : UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell")! let videoURL = NSURL(string: "http://www.ebookfrenzy.com/ios_book/movie/movie.mov") let player = AVPlayer(url: videoURL! as URL) let playerLayer = AVPlayerLayer(player: player) playerLayer.frame = cell.bounds cell.layer.addSublayer(playerLayer) player.play() return cell }