如何缓存AVPlayerItem(视频)以便在UITableview中重用

时间:2013-02-13 15:40:37

标签: ios uitableview caching video avplayer

我在UITableView中显示了许多视频。视频远程存储在服务器上。我可以使用以下一些代码将视频加载到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使单元格出列,然后再次重新排队,再次从网址加载视频。我想知道是否有办法下载和缓存或保存视频,以便可以从手机播放而无需再次连接。我试图在Apple提供的LazyTableImages示例中使用技术,但我有点卡住了。

3 个答案:

答案 0 :(得分:5)

在解决了尝试缓存AVPlayerItems失败之后,我得出的结论是,如果你缓存AVPlayerItem的底层AVAsset并且意图重用它会更好,而AVPlayerItem本身并不意味着可以重用

答案 1 :(得分:2)

有一种方法可以做到这一点,但它可能会对旧设备造成负担,导致您的应用被MediaServerD抛弃。

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

答案 2 :(得分:0)

Just worked on this problem with a friend yesterday. The code we used basically uses the NSURLSession built-in caching system to save the video data. Here it is:

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

Second, you will need to set the caching configuration for the NSURLSession. My KHURLSessionManager takes care of this with the following code:

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

Lastly, you should make sure your cache is large enough for the files, I put the following in my AppDelegate.

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

Hope this helps.