昨天刚和朋友一起解决这个问题。我们使用的代码基本上使用了 NSURLSession 内置的缓存系统来保存视频数据。这里是:
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 设置缓存配置。我的 KHURLSessionManager 使用以下代码处理此问题:
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.requestCachePolicy = NSURLRequestReturnCacheDataElseLoad;
_session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
最后,您应该确保您的缓存足够大以容纳文件,我将以下内容放在我的 AppDelegate 中。
[NSURLCache sharedURLCache].diskCapacity = 1000 * 1024 * 1024; // 1000 MB
希望这可以帮助。