Caching videos in ios

2019-07-28 03:01发布

I have the following method playing video on AVMediaPlayerController

-(void)sendRequestForVideo
{

        NSString*VideoStr=@"http://www.ebookfrenzy.com/ios_book/movie/movie.mov";
         NSURL  *url = [NSURL URLWithString:VideoStr];
       AVPlayer *player = [AVPlayer playerWithURL:url];

        AVPlayerViewController *controller = [[AVPlayerViewController alloc]init];
        controller.player = player;

        [self addChildViewController:controller];
        [self.view addSubview:controller.view];
        controller.view.frame = self.view.frame;
        [player play];


}

I want to cache the video played here like we cache image but I am not able to cache it and not understanding how should I move to achieve this thing as there are so many things relted to AVfoundation frammework .Kindly give some suggestions that how vides can be stored in nsurl cache .Thanks in advance!

1条回答
Lonely孤独者°
2楼-- · 2019-07-28 03:08

There straight forward way is to download the video by using NSUrlSession and use build in cache system to save video data. You can check out the details in this SO answer. But this way you are actually downloading the video twice and re-using it. So you might end up using more data from user phone.

Another way to use AVAssetExportSession and save the played video into file system and reuse it when needed.

Objective C

AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetHighestQuality];
exporter.outputURL = exportUrl; // consider you have a export url 
[exporter exportAsynchronouslyWithCompletionHandler:^{
    // here your file will be saved into file system 
}];

Swift

let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality)
let filename = "filename.mp4"
let documentsDirectory = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).last!
let outputURL = documentsDirectory.URLByAppendingPathComponent(filename)

exporter?.outputURL = outputURL
exporter?.outputFileType = AVFileTypeMPEG4
exporter?.exportAsynchronouslyWithCompletionHandler({

    print(exporter?.status.rawValue)
    print(exporter?.error)
})

With the help of AVAssetExportSession we are actually re-using the played video so user phone data will not be wasted and it is easy for us to reuse as well. Check the below documentation links to understand better

查看更多
登录 后发表回答