Reputation: 889
How to play video in AVPlayer from coredata as nsdata formate? MPMoviePlayerController deprecated so I am going with AVPlayer. I am search some thing said about url path for saved nsdata location I am not clear about that. Anyone explain this? How can I play?
I am new for this I appreciate if share that code.
If any one share good tutorial for custom AVPlayer I didn't find good one so learn from github sample project.
Advance Thanks :)
Upvotes: 0
Views: 4141
Reputation: 3246
Here's a Swift version on how to do this
let data = //... your video Data/NSData
let cacheURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!.appendingPathComponent("yourvidename.mp4")
do {
try data.write(to: cacheURL, options: .atomicWrite)
} catch let err {
print("Failed with error:", err.localizedString)
}
// instantiate the player
let player = AVPlayer(url: cacheURL)
let vcPlayer = AVPlayerViewController()
vcPlayer.player = player
vcPlayer.player?.play()
// present it or add it to whatever view you need
present(vcPlayer, animated: true, completion: nil)
Then on viewWillDisappear
delete the content of the cachesDirectory
if you want
Upvotes: 1
Reputation: 3385
You can try this!
NSString *filePath = [self documentsPathForFileName:@"video.mp4"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
if(!fileExists) {
NSData *videoAsData; // your data here
[videoAsData writeToFile:filePath atomically:YES];
}
// access video as URL
NSURL *videoFileURL = [NSURL fileURLWithPath:filePath];
// create an AVPlayer
AVPlayer *player = [AVPlayer playerWithURL:videoFileURL];
// create a player view controller
AVPlayerViewController *controller = [[AVPlayerViewController alloc]init];
controller.player = player;
[self presentViewController:controller animated:YES completion:^{
[controller.player play];
}];
- (NSString *)documentsPathForFileName:(NSString *)name
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
return [documentsPath stringByAppendingPathComponent:name];
}
// if you want to remove file after playing video
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
BOOL success = [fileManager removeItemAtPath:filePath error:&error];
Upvotes: 1