Could not save .mp4 video file to iphone camera roll? - iphone

I received the video file contents in the format of NSData and I am playing that file in MPMoviePlayerController successfully with following code
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *FileExtension=[[NSString alloc]init];
if([contentType hasPrefix:#"video"] || [contentType isEqualToString:#"application/video"]) {
FileExtension=#"mov";
//FileExtension=#"mp4";
}
else
{
FileExtension=[contentType lastPathComponent];
}
//appFile is type of NSString.
appFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"MyFile.%#",FileExtension]];
//videoData is type of NSData
[videoData writeToFile:appFile atomically:YES];
NSURL *fileURL = [NSURL fileURLWithPath:appFile isDirectory:NO];
moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:fileURL];
moviePlayerController.view.frame = self.view.bounds;
moviePlayerController.movieSourceType = MPMovieSourceTypeFile;
moviePlayerController.fullscreen = YES;
moviePlayerController.shouldAutoplay=NO;
[self.view addSubview:moviePlayerController.view];
[moviePlayerController prepareToPlay];
but I am unable to write/save this video file to camera roll,this is my code for writing code to the camera roll.
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
NSURL *filePathURL = [NSURL fileURLWithPath:appFile isDirectory:NO];
if ([library videoAtPathIsCompatibleWithSavedPhotosAlbum:filePathURL]) {
[library writeVideoAtPathToSavedPhotosAlbum:filePathURL completionBlock:^(NSURL *assetURL, NSError *error){
if (error) {
NSLog(#"Not success");
} else {
NSLog(#"success");
}
}];
}
this code is work fine when I set mimeType/file_format as .mov & .3Gp but I have problem related to save video to the camera roll when mimeType/file_format as .mp4 file.

You can convert your .mp4 to .mov if you change your appFile this way:
Your code:
appFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"MyFile.%#",FileExtension]];
New code:
appFile = [documentsDirectory stringByAppendingPathComponent:#"MyFile.mov"];
The SO automatically converts .mp4 to .mov

Related

How can i play video (By Name) from document directory ?

In my application i store my video in document directory with name is 'video2.MOV' and i want to play it.
Here problem is that i am not able to get this video (name is 'video2.MOV') from document directory.
My Code :
-(void)playVideo:(NSTimer *)theTimer
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"video2.MOV"];
NSLog(#"filePath - %#",filePath);
NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
NSLog(#"contentPath - %#",content);
MPMoviePlayerViewController *videoPlayerView = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:content]];
[[CCDirector sharedDirector] presentMoviePlayerViewControllerAnimated:videoPlayerView];
[videoPlayerView.moviePlayer play];
}
In console, each time i got contentPath is NULL, so may be i am not able to play video.
Here, What is my mistake. please give me suggestion on this issue.
Try this:
- (NSString*)GetDocumentFilePath:(NSString*)filename
{
NSLog(#"%#",filename);
// NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
NSString *documentsDirectory = [paths objectAtIndex:0]; //2
NSString* file = [[NSString alloc]initWithFormat:#"%#",filename];
NSString* path = [documentsDirectory stringByAppendingPathComponent:file];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]) //4
{
//NSString *bundle = [[NSBundle mainBundle] pathForResource:filename ofType:#"plist"]; //5
//[fileManager copyItemAtPath:bundle toPath:path error:&error]; //6
}
return path;
}
and get file path like this:
NSURL *URL = [NSURL fileURLWithPath:[self GetDoucmentPath:path]];
MPMoviePlayerController* theMovie=[[MPMoviePlayerController alloc] initWithContentURL:pptURL];
theMovie.scalingMode=MPMovieScalingModeAspectFill;
theMovie.view.frame = CGRectMake(60, 20, 700, 500);
theMovie.view.center = self.view.center;
//[self.view addSubview:theMovie.view];
// Register for the playback finished notification.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(onStop)
name:MPMoviePlayerPlaybackDidFinishNotification
object:theMovie];
// Movie playback is asynchronous, so this method returns immediately.
[self.view addSubview:theMovie.view];
[theMovie play];
Hope it Helps!!
Instead of using content use filePath instead to get to the movie file:
MPMoviePlayerViewController *videoPlayerView = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:filePath]];

MPMoviePlayerController doesn't play newly saved video file

I'm using an imagePickerController to record video. In the imagePickerController:didFinishPickingMediaWithInfo: function I'm trying to set the video to a previously defined MPMoviePlayerController:
if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]){
NSURL *movieUrl = [info objectForKey:UIImagePickerControllerMediaURL];
[self.moviePlayer setContentURL:movieUrl]];
}
This is working fine and the video is indeed playing.
But I want to save the file for later use. When I do this and use the saved file for the moviePlayer, nothing happens:
I've tried this (saving the data to a new file)
NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *newPath = [directory stringByAppendingPathComponent:#"myMovie.mov"];
NSData *videoData = [NSData dataWithContentsOfURL:movieUrl];
[videoData writeToFile:newPath atomically:NO];
[self.moviePlayer setContentURL:[NSURL URLWithString:newPath]];
or this (copying the temp video file to my document folder)
NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *newPath = [directory stringByAppendingPathComponent:#"myMovie.mov"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
[fileManager copyItemAtPath:[videoUrl path] toPath:newPath error:&error];
[self.moviePlayer setContentURL:[NSURL URLWithString:newPath]];
Without any success, even though the file at newPath does exist... What am I doing wrong?
Ok I finally found the issue. The problem was not in fact with the MPMoviePlayerController but with the line:
[self.moviePlayer setContentURL:[NSURL URLWithString:newPath]];
I fixed it by replacing that line with:
[self.moviePlayer setContentURL:[NSURL fileURLWithPath:newPath isDirectory:NO]];
Hope that will help someone else!
use the code below:
NSData *movieData;
NSError *dataReadingError = nil;
movieData = [NSData dataWithContentsOfURL: movieURL options:NSDataReadingMapped error:&dataReadingError];
if(movieData != nil)
NSLog(#"Successfully loaded the data.");
else
NSLog(#"Failed to load the data with error = %#", dataReadingError);

iPhone: Trouble Playing Video in iOS 5

In my iPhone app, I am taking video using ImagePickerview and storing it to document directory
For iOS4 (device iPod) I can play video stored in document directory but for iOS 5 (device iPad) the same code is not working for playing video.
so for iOS 5 is there any different way for storing and playing video from document directory
(I also tried with library directory)
-(IBAction)saveVideo:(id)sender
{
imagepicker = [[UIImagePickerController alloc] init];
imagepicker.delegate=self;
if([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerSourceTypeCamera])
{
[imagepicker setSourceType:UIImagePickerControllerSourceTypeCamera];
[imagepicker setMediaTypes:[UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera]];
[imagepicker setCameraDevice:UIImagePickerControllerCameraCaptureModeVideo];
[self presentModalViewController:imagepicker animated:YES];
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSMutableString *tempPath = [[[info valueForKey:#"UIImagePickerControllerMediaURL"] absoluteString] mutableCopy];
NSString *newPath1 = [NSString stringWithFormat:#"myVideo.mov"];
[tempPath replaceOccurrencesOfString:#"file://localhost/private/" withString:#"/" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [tempPath length])];
NSFileManager *manager = [NSFileManager defaultManager];
NSError *error = nil;
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject], newPath1];
NSString *newPath = [NSString stringWithFormat:#"%#/%#", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject], newPath1];
BOOL success = [manager copyItemAtPath:tempPath toPath:newPath error:&error];
if(error){
NSLog(#"New Path: %#", newPath);
NSLog(#"Error: %#", error);
}
if(success)
{
NSLog(#"Succeed");
}
[self dismissModalViewControllerAnimated:YES];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissModalViewControllerAnimated:YES];
}
-(IBAction)playVideo:(id)sender
{
NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [path objectAtIndex:0];
NSString *myDBnew = [documentsDirectory stringByAppendingPathComponent:#"myVideo.mov"];
NSURL *url = [[NSURL alloc] initWithString:myDBnew];
NSLog(#"URL== %#",url);
moviePlayer = [[MPMoviePlayerController alloc]
initWithContentURL:url];
// [[NSNotificationCenter defaultCenter] addObserver:self
// selector:#selector(moviePlayBackDidFinish:)
// name:MPMoviePlayerPlaybackDidFinishNotification
// object:moviePlayer];
moviePlayer.controlStyle = MPMovieControlStyleDefault;
moviePlayer.shouldAutoplay = YES;
[self.view addSubview:moviePlayer.view];
[moviePlayer setFullscreen:YES animated:YES];
}
What could be wrong?
Here is the code.
If I add the video file into my project and use below code it is playing Video The only thing is it is not playing video from document directory
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:#"myVideo" ofType:#"mov"]];
moviePlayer = [[MPMoviePlayerController alloc]
initWithContentURL:url];
Even in iTunes via flittering I can see the file:"myVideo.mov", after running the app in device means This codes recording and storing video but not able to read or play.
Here in my code the problem was the way i am creating url
NSURL *url = [[NSURL alloc] initWithString:myDBnew];
which doesn't work for ios5 so i replaced in code by
NSURL *url = [[NSURL alloc] initFileURLWithPath:<#(NSString *)#> isDirectory:<#(BOOL)#>];

UIWebView displays locally stored document on simulator but not device

I have an issue where I'm trying to view a document (Word document, image, or video) that I have stored locally. I'm using UIWebView and on the Simulator it works perfectly, but on the device, it's a blank screen (no errors thrown in console). Here's my code to view the document:
UIWebView *newWebView;
if (appDelegate.IS_IPAD)
{
newWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 768, 1024)];
}
else
{
newWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
}
newWebView.scalesPageToFit = YES;
[self setWebView: newWebView];
[newWebView release], newWebView = nil;
[[self webView] setDelegate: self];
[[self view] addSubview:[self webView]];
NSURL *nsURL = [NSURL fileURLWithPath:filePath isDirectory:NO];
[[self webView] loadRequest:[NSURLRequest requestWithURL:nsURL]];
Here's how I'm saving the document locally before viewing. I do think the file is getting successfully saved on the device as it does on the simulator.
// Save the file on the device
NSURL *contentUrl = [NSURL URLWithString:selectedContent.contentUrl];
NSString *fileName = [[contentUrl absoluteString] lastPathComponent];
NSString *homeDirectoryPath = NSHomeDirectory(); // Create the path
NSString *unexpandedPath = [homeDirectoryPath stringByAppendingString:#"/MyApp/"];
NSString *folderPath = [NSString pathWithComponents:[NSArray arrayWithObjects:[NSString stringWithString:[unexpandedPath stringByExpandingTildeInPath]], nil]];
NSString *unexpandedImagePath = [folderPath stringByAppendingFormat:#"/%#", fileName];
NSString *filePath = [NSString pathWithComponents:[NSArray arrayWithObjects:[NSString stringWithString:[unexpandedImagePath stringByExpandingTildeInPath]], nil]];
if (![[NSFileManager defaultManager] fileExistsAtPath:folderPath isDirectory:NULL])
{
[[NSFileManager defaultManager] createDirectoryAtPath:nil withIntermediateDirectories:NO attributes:nil error:nil];
}
// Do the actual write of the file to the device
NSData *fileData = [NSData dataWithContentsOfURL:myUrl]; // Create the file data reference
[fileData writeToFile:filePath atomically:YES]; //Save the document to the home directory
Watch out for case issues. The simulator is not case sensitive whereas the iPhone is!
I solved this by saving my document to the default Documents Directory. Here's the code I used to accomplish this:
NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [arrayPaths objectAtIndex:0];
NSString *filePath = [docDirectory stringByAppendingString:#"/"];
filePath = [filePath stringByAppendingString:fileName];
NSData *fileData = [NSData dataWithContentsOfURL:myUrl];
[fileData writeToFile:filePath atomically:YES];

how to stream a video in iphone

does initWithContentURL: in MPMoviePlayerController download the video file at first and then start playing or will it stream file like in youtube?
I want to play an video located in server through streaming in order not to waste of time.
How to perform streaming in iphone?
Can anyone please suggest me if u know.
Thanks in advance.
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (!documentsDirectory) {
NSLog(#"Documents directory not found!");
}
NSString *appFile;
NSArray *myWords = [[NSString stringWithFormat:#"%#",[[videolistArray objectAtIndex:[number intValue]] valueForKey:#"video"]] componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"/"]];
appFile = [documentsDirectory stringByAppendingPathComponent:[myWords lastObject]];
NSFileManager *fileMgr=[NSFileManager defaultManager];
if (![fileMgr fileExistsAtPath:appFile]) {
NSData *imageData;
NSURL *imageURL = [[[NSURL alloc] initWithString:[[videolistArray objectAtIndex:[number intValue]] valueForKey:#"video"] ] autorelease];
if (imageURL) {
imageData = [NSData dataWithContentsOfURL:imageURL];
}
[imageData writeToFile:appFile atomically:YES];
}
[pool release];
if (spinner) {
[spinner stopAnimating];
[spinner removeFromSuperview];
[spinner release];
spinner = nil;
}
---------------------------Above methode is for save video in file system of iphone
-------------------- Below method to play that movie continuos
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (!documentsDirectory) {
NSLog(#"Documents directory not found!");
}
NSArray *myWords = [videoString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"/"]];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:[myWords lastObject]];
NSLog(#"%#",[myWords lastObject]);
NSURL *url = [NSURL fileURLWithPath:appFile];
self.videoMPPlayer =[[MPMoviePlayerController alloc] initWithContentURL:url];
self.videoMPPlayer.view.frame = CGRectMake(0, 0, 320, 480);
self.videoMPPlayer.scalingMode = MPMovieScalingModeAspectFill;
self.videoMPPlayer.controlStyle = MPMovieControlStyleNone;
// Register for the playback finished notification
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(movieLoadStateChanges:) name:MPMoviePlayerLoadStateDidChangeNotification object:videoMPPlayer];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(myMovieFinishedCallback:) name:MPMoviePlayerPlaybackDidFinishNotification object:videoMPPlayer];
// Movie playback is asynchronous, so this method returns immediately.
[self.videoMPPlayer play];