如何caching一个AVPlayerItem(video)在UITableview中重用

我在UITableView中显示了一些video。 video远程存储在服务器上。 我可以使用下面的一些代码将video加载到tableview中。

NSString *urlString = [NSString stringWithFormat:[row objectForKey:@"video_uri"]]; NSURL* url = [NSURL URLWithString:urlString]; AVPlayerItem *pItem = [AVPlayerItem playerItemWithURL:url]; AVPlayer *player = [AVPlayer playerWithPlayerItem:pItem]; 

每次tableview退出单元格然后重新再次从url中加载video。 我想知道是否有一种方法来下载,caching或保存video,以便它可以从手机播放而无需再次连接。 我试图画出苹果提供的LazyTableImages示例中使用的技术,但是我有点卡住了。

在尝试cachingAVPlayerItems之后,我得出了这样的结论:如果cachingAVPlayerItem的基础AVAsset,而AVPlayerItem本身并不意味着要被重用,那么效果会更好。

有一种方法可以做到这一点,但它可能会对旧设备征税,随后导致您的应用程序被MediaServerD抛弃。

创build时,将每个玩家保存到NSMutableArray中。 数组中的每个索引都应该对应于UITableView的indexPath.row。

刚刚和一个朋友在这个问题上昨天一起工作。 我们使用的代码基本上使用NSURLSession内置的caching系统来保存video数据。 这里是:

  NSURLSession *session = [[KHURLSessionManager sharedInstance] session]; NSURLRequest *req = [[NSURLRequest alloc] initWithURL:**YOUR_URL**]; [[session dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { // generate a temporary file URL NSString *filename = [[NSUUID UUID] UUIDString]; NSURL *temporaryDirectoryURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES]; NSURL *fileURL = [[temporaryDirectoryURL URLByAppendingPathComponent:filename] URLByAppendingPathExtension:@"mp4"]; // save the NSData to that URL NSError *fileError; [data writeToURL:fileURL options:0 error:&fileError]; // give player the video with that file URL AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:fileURL]; AVPlayer *player = [AVPlayer playerWithPlayerItem:playerItem]; _avMovieViewController.player = player; [_avMovieViewController.player play]; }] resume]; 

其次,你将需要为NSURLSession设置cachingconfiguration。 我的KHURLSessionManager用下面的代码来处理这个问题:

  NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; config.requestCachePolicy = NSURLRequestReturnCacheDataElseLoad; _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]]; 

最后,你应该确保你的caching足够大的文件,我把以下放在我的AppDelegate。

  [NSURLCache sharedURLCache].diskCapacity = 1000 * 1024 * 1024; // 1000 MB 

希望这可以帮助。