How to cache an AVPlayerItem (Video) for reuse in a UITableview

前端 未结 3 1342
伪装坚强ぢ
伪装坚强ぢ 2020-12-30 13:18

I have a number of videos that I am displaying in a UITableView. The videos are stored remotely on a server. I am able to load the videos into the tableview using some of th

3条回答
  •  旧巷少年郎
    2020-12-30 13:50

    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.

提交回复
热议问题