Save the The Stream From URL - iphone

In my project I am connecting a url and I am watching a video with MPMoviePlayerViewController. But that is not enough to me. I also want to save the file to my Iphone. I have to buttons. one is watch the video, the other is save the video. When I push the button watch I am watchng it. But unable to save it. by this I want to be able to watch the video later. So in another view I want to see saved videos etc. Is there any one can help me or can show the way ? I have tried following code phrase but When the code started, It works for a while (probably it is the download time), but when it is time to save I get Bad EXC_BAD_ACCESS error .Thanks every one.
Here is my code .
CFStringRef *docsDirectory = (CFStringRef)[NSTemporaryDirectory() stringByAppendingPathComponent: #"recordedFile.mp4"];
NSString *temPath=NSTemporaryDirectory();
NSString *tempfile=[temPath stringByAppendingPathComponent:#"recode.mp4"];
NSLog(#" DOSYA ADI MADI %#",docsDirectory);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = [[NSError alloc] init];
[fileManager removeItemAtPath:docsDirectory error:&error];
NSURL *url = [NSURL URLWithString:#"http://video.teknomart.com.tr/3-13-2.mp4"];
NSMutableURLRequest *liveRequest = [[NSMutableURLRequest alloc] initWithURL:url];
[liveRequest setCachePolicy:NSURLRequestReloadIgnoringCacheData];
[liveRequest setValue:#"headervalue" forHTTPHeaderField:#"headerfield"];
NSURLResponse *response;
NSData *myData = [NSURLConnection sendSynchronousRequest:liveRequest returningResponse:&response error:&error];
NSData *myData2 = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://video.teknomart.com.tr/3-13-2.mp4"]];
NSString *myString=[[NSString alloc] initWithData:myData encoding:NSASCIIStringEncoding];
NSLog(#"gelen sey %#",myString);
[myString writeToFile:tempfile writeToFile:tempfile automatically:YES encoding:NSASCIIStringEncoding error:nil];
[myString release];
return true;

-(void)viewDidLoad {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (!documentsDirectory) {
NSLog(#"Documents directory not found!");
}
NSArray *myWords = [songNameString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"/"]];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:[myWords lastObject]];
NSLog(#"%#",[myWords lastObject]);
NSURL *url = [NSURL fileURLWithPath:appFile];
NSLog(#"%#",url);
[[UIApplication sharedApplication] setStatusBarHidden:YES];
self.navigationController.navigationBarHidden=YES;
currentTimer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(showCurrentTime) userInfo:nil repeats:YES];
alarmTimeLabel.text =alarmTimeString;
alarmSongLabel.text = [myWords lastObject] ;
[self performSelector:#selector(loadVideoInBackground)];
//[NSThread detachNewThreadSelector:#selector(loadVideoInBackground) toTarget:self withObject:nil];
}
-(void)loadVideoInBackground
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (!documentsDirectory) {
NSLog(#"Documents directory not found!");
}
NSString *appFile;
NSArray *myWords = [songNameString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"/"]];
appFile = [documentsDirectory stringByAppendingPathComponent:[myWords lastObject]];
NSFileManager *fileMgr=[NSFileManager defaultManager];
if (![fileMgr fileExistsAtPath:appFile]) {
alarmCanPlay = FALSE;
NSURL *imageURL = [[[NSURL alloc] initWithString:songNameString]autorelease];
NSURLRequest *imageRequest = [NSURLRequest requestWithURL:imageURL
cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:120.0];
imageConnection = [[NSURLConnection alloc] initWithRequest:imageRequest delegate:self];
if(imageConnection)
{
videoData = [[NSMutableData data] retain];
}
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// this method is called when the server has determined that it
// has enough information to create the NSURLResponse
// it can be called multiple times, for example in the case of a
// redirect, so each time we reset the data.
// receivedData is declared as a method instance elsewhere
[videoData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// append the new data to the receivedData
// receivedData is declared as a method instance elsewhere
//NSLog(#"%d",[data size]);
[videoData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// release the data object
[videoData release];
// inform the user
NSLog(#"Connection failed! Error - %# %#", [error localizedDescription], [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
//workInProgress = NO;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (!documentsDirectory) {
NSLog(#"Documents directory not found!");
}
NSString *appFile;
NSArray *myWords = [songNameString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"/"]];
appFile = [documentsDirectory stringByAppendingPathComponent:[myWords lastObject]];
[videoData writeToFile:appFile atomically:YES];
alarmCanPlay = TRUE;
}

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (!documentsDirectory) {
NSLog(#"Documents directory not found!");
}
NSArray *myWords = [songNameString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"/"]];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:[myWords lastObject]];
NSLog(#"%#",[myWords lastObject]);
NSURL *url = [NSURL fileURLWithPath:appFile];
NSLog(#"%#",appFile);
self.videoMPPlayer =[[MPMoviePlayerController alloc] init];
videoMPPlayer.view.frame = CGRectMake(0, 0, 768, 1024);
videoMPPlayer.scalingMode = MPMovieScalingModeAspectFill;
videoMPPlayer.controlStyle = MPMovieControlStyleNone;
videoMPPlayer.shouldAutoplay = NO;
[videoMPPlayer pause];

This is What I have in my code. It looks like it is downloading movie . But I cant find the file. also I run it in the similator . nofile that named with my moviename was in tmp dir. What is wrong or missing ?
-(void)viewDidLoad
{
[super viewDidLoad];
NSString *documentsDirectory = NSTemporaryDirectory();
if (!documentsDirectory) {
NSLog(#"Documents directory not found!");
}
downloaded=FALSE;
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:#"mymoview.mp4"];
NSURL *url = [NSURL fileURLWithPath:appFile];
NSLog(#"%#",url);
[[UIApplication sharedApplication] setStatusBarHidden:NO];
self.navigationController.navigationBarHidden=NO;
timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(showVideo) userInfo:nil repeats:YES];
[self performSelector:#selector(loadVideoInBackground)];
[NSThread detachNewThreadSelector:#selector(loadVideoInBackground) toTarget:self withObject:nil];
}
-(void)showVideo{
NSString *homeDir = NSHomeDirectory();
NSString *tempDir = NSTemporaryDirectory();
// Format output
NSString *s =
[NSString stringWithFormat:#"homeDir:\n"
#"%#\n"
#"tempDir:\n"
#"%#\n",
homeDir,
tempDir];
NSLog(#" %# ",s);
if (downloaded) {
NSLog(#"burdayim");
NSString *documentsDirectory = NSTemporaryDirectory();
if (!documentsDirectory) {
NSLog(#"Documents directory not found!");
}
NSString *appFile;
appFile = [documentsDirectory stringByAppendingPathComponent:#"mymoview.mp4" ];
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"myvoview" ofType:#"mp4" inDirectory:#"/tmp"];
NSLog(#" %# lafta oynatilan dosya ",filePath);
NSFileManager *fileMgr=[NSFileManager defaultManager];
if (![fileMgr fileExistsAtPath:filePath]) {
NSLog(#"dosya yok");
}
else
{
NSLog(#"dosyayi da buldum");
NSURL *movieURL = [NSURL fileURLWithPath:appFile];
NSLog(#" %# lafta oynatilan dosya ",appFile);
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
[player setFullscreen:YES];
[self shouldAutorotateToInterfaceOrientation:UIInterfaceOrientationLandscapeLeft];
player.fullscreen=YES;
//self.view.autoresizesSubviews=YES;
//[self presentModalViewController:player animated:YES];
self.view=player.view;
[player play];
}
}
}
-(void)loadVideoInBackground{
NSString *documentsDirectory = NSTemporaryDirectory();
if (!documentsDirectory) {
NSLog(#"Documents directory not found!");
}
NSString *appFile;
appFile = [documentsDirectory stringByAppendingPathComponent:#"mymoview.mp4" ];
NSFileManager *fileMgr=[NSFileManager defaultManager];
if (![fileMgr fileExistsAtPath:appFile]) {
NSURL *videoURL = [[[NSURL alloc] initWithString:#"http://video.teknomart.com.tr/3-13-2.mp4"] autorelease];
NSURLRequest *videoRequest = [NSURLRequest requestWithURL:videoURL
cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:120.0];
videoconnection = [[NSURLConnection alloc] initWithRequest:videoRequest delegate:self];
if(videoconnection)
{
videoData = [[NSMutableData data] retain];
}
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//[videoData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// append the new data to the receivedData
// receivedData is declared as a method instance elsewhere
NSLog(#" bisiler yukleniyor ");
[videoData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[videoData release];
NSLog(#"Connection failed! Error - %# %#", [error localizedDescription], [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (!documentsDirectory) {
NSLog(#"Documents directory not found!");
}else
{
NSString *appFile;
appFile = [documentsDirectory stringByAppendingPathComponent:#"mymoview.mp4"];
[videoData writeToFile:appFile atomically:YES];
downloaded = TRUE;
NSLog(#"Yuklandi");
}
}
}

Related

iOS reading txt from web

I am trying to read a file from a web, but it is not working! So please need some help!!
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *docDirPath = [paths objectAtIndex:0];
NSString *filePath = [docDirPath
stringByAppendingPathComponent:#"filess.txt"];
NSURL* url;
NSString* content;
NSFileManager* fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:filePath])
{
content = [[NSString alloc]
initWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding error:nil];
}
else
{
url = [[NSURL alloc]
initWithString:#"http://sdsd/about/readme.txt"];
content = [[NSString alloc]
initWithContentsOfURL:url
encoding:NSUTF8StringEncoding error:nil];
[url release];
[content writeToFile:filePath atomically:YES
encoding:NSUTF8StringEncoding error:nil];
}
Thanks
use this code to download text file
NSURLRequest *theRequest=[NSURLRequest requestWithURL:theURL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
NSData *returnData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:&urlerror];
NSString *file = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
///do request like this
NSString *strUrl=[NSString stringWithFormat:#"your url"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strUrl]];
downloadConn = [NSURLConnection connectionWithRequest:request
delegate:self];
[downloadConn start];
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse * )response
{
responseData=[[NSMutableData alloc]init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"%#",[error description]);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
Get your response in NSdata and write it as follows
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *dataPath = [path stringByAppendingPathComponent:#"yourfile.txt"];
dataPath = [dataPath stringByStandardizingPath];
[responseData writeToFile:dataPath atomically:YES];
}

Reading downloaded file objective-c

I am trying to read text file downloaded from my server.
-(void)downloadFile
{
NSURLRequest request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://myserver.com/website/file.txt"]];
AFURLConnectionOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"file.txt"];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];
[operation setCompletionBlock:^{
NSLog(#"downloadComplete!");
NSString *path;
path = [[NSBundle mainBundle] pathForResource: #"file" ofType: #"txt"];
NSString *data = [self readFile: path];
NSLog(#"%#",data);
}];
[operation start];
}
-(NSString *)readFile:(NSString *)fileName
{
NSLog(#"readFile");
NSString *appFile = fileName;
NSFileManager *fileManager=[NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:appFile])
{
NSError *error= NULL;
NSString *resultData = [NSString stringWithContentsOfFile: appFile encoding: NSUTF8StringEncoding error: &error];
if (error == NULL)
return resultData;
}
return NULL;
}
It downloads the file successfully but I can't read file. Returns null. Probably I can't set file path correctly. I want to read file from device disk, not project bundle.
Change
path = [[NSBundle mainBundle] pathForResource: #"file" ofType: #"txt"];
to
path = filePath;
I made your stuff work, i dont know if you still need it
-(void)downloadFile
{
CNMRouter *routext;
routext = ((LDAppDelegate *)[UIApplication sharedApplication].delegate).router;
[[[Singleton sharedClient]httpClient] setParameterEncoding:AFFormURLParameterEncoding];
NSMutableURLRequest *request;
if([routext postOrGet]){
request = [[[Singleton sharedClient]httpClient] requestWithMethod:#"GET"
path:[routext getLoginURLPath:#"admin" andPassword:#"admin"]
parameters:nil];
}else{
request = [[[Singleton sharedClient]httpClient] requestWithMethod:#"POST"
path:[routext getBackupUrl]
parameters:[routext getBackupURLPath]];
}
// NSURLRequest request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://myserver.com/website/file.txt"]];
AFURLConnectionOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlock:^{
NSLog(#"downloadComplete!");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(#"%#", [paths objectAtIndex:0]);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"file.txt"];
// operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];
NSString *path;
// path = [[NSBundle mainBundle] pathForResource: #"file" ofType: #"txt"];
path = filePath;
NSString *data = [self readFile: path];
NSLog(#"%#",data);
}];
[operation start];
}
I moved some stuf from its place but basicaly you were trying to get your file before it was even downloaded so i just put some stuff inside the succes block. Its working for me, thank you!

ASIHTTP Request cancelled error in iphone sdk

I am uploading multiple images data using ASIHTTP request method. All Images uploaded successfully but for only last image ASIHttp request goes fail. I tried a lot but i can't get anymore.
Can someone help me?
My code is as follow:
for(int i=0;i<[arySteps count];i++)
{
NSMutableArray *StepDetail=[[NSMutableArray alloc] initWithArray:[DatabaseAccess getAddSteps:str]];
if([[[StepDetail objectAtIndex:0] valueForKey:#"s_image"] length]!=0)
{
NSMutableArray *imgary=[[[[StepDetail objectAtIndex:0] valueForKey:#"s_image"] componentsSeparatedByString:#","] mutableCopy];
imagedata1=[[NSData alloc] init];
imagedata2=[[NSData alloc] init];
imagedata3=[[NSData alloc] init];
for (int i=0; i<[imgary count]; i++)
{
if(i==0)
{
NSString *filename=[NSString stringWithFormat:#"%#.jpeg",[imgary objectAtIndex:0]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:filename];
NSURL *movieURL = [NSURL fileURLWithPath:filePath];
imagedata1=[NSData dataWithContentsOfURL:movieURL];
NSLog(#"%#",imagedata1);
}
else if(i==1)
{
NSString *filename=[NSString stringWithFormat:#"%#.jpeg",[imgary objectAtIndex:1]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:filename];
NSURL *movieURL = [NSURL fileURLWithPath:filePath];
imagedata2=[NSData dataWithContentsOfURL:movieURL];
NSLog(#"%#",imagedata2);
}
else if(i==2)
{
NSString *filename=[NSString stringWithFormat:#"%#.jpeg",[imgary objectAtIndex:2]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:filename];
NSURL *movieURL = [NSURL fileURLWithPath:filePath];
imagedata3=[NSData dataWithContentsOfURL:movieURL];
NSLog(#"%#",imagedata3);
}
}
NSString *strurl=[NSString stringWithFormat:#"http://inst.niftysol.com/app/webroot/webservices/test.php?said=%d&stepid=%#", appdel.idPARENTID,s_id_live];
[self setHttprequest:[ASIFormDataRequest requestWithURL:[NSURL URLWithString:strurl]]];
//NSString *userid=[NSString stringWithFormat:#"%d",appdel.idUID];
// [httprequest setPostValue:userid forKey:#"s_user_id"];
[httprequest setShouldContinueWhenAppEntersBackground:YES];
[httprequest setDelegate:self];
[httprequest setDidFinishSelector:#selector(uploadFinished:)];
[httprequest setDidFailSelector:#selector(uploadFailed:)];
[httprequest setData:imagedata1 withFileName:#"1.jpeg" andContentType:#"image/jpeg" forKey:#"userfile1"];
[httprequest setData:imagedata2 withFileName:#"2.jpeg" andContentType:#"image/jpeg" forKey:#"userfile2"];
[httprequest setData:imagedata3 withFileName:#"3.jpeg" andContentType:#"image/jpeg" forKey:#"userfile3"];
countupload=countupload+1;
[httprequest startAsynchronous];
}
}
In above code I've got all images data properly but for last image request goes fail. I get the error:
Error Domain=ASIHTTPRequestErrorDomain Code=4 "The request was cancelled" UserInfo=0x96fbfe0 {NSLocalizedDescription=The request was cancelled}
You should switch to AFNetworking if possible, very easy to integrate. Though answer your question you should switch to network queue for ASIHTTPRequest.
Declare ASINetworkQueue *networkQueue; in header file, declare property #property (retain) ASINetworkQueue *networkQueue; and synthesize it as well in implementation file.
-(void)doUploadOperation //You can call this method for your upload operation.
{
[[self networkQueue] cancelAllOperations];
// Creating a new queue each time we use it means we don't have to worry about clearing delegates or resetting progress tracking
[self setNetworkQueue:[ASINetworkQueue queue]];
[[self networkQueue] setDelegate:self];
[[self networkQueue] setRequestDidFinishSelector:#selector(requestFinished:)];
[[self networkQueue] setRequestDidFailSelector:#selector(requestFailed:)];
[[self networkQueue] setQueueDidFinishSelector:#selector(queueFinished:)];
int i;
for (i=0; i<[arySteps count]; i++)
{
//First create image data
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filename=[NSString stringWithFormat:#"%#.jpeg",[imgary objectAtIndex:i]];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:filename];
NSURL *movieURL = [NSURL fileURLWithPath:filePath];
NSData *imagedata=[NSData dataWithContentsOfURL:movieURL];
//Create request and add to network queue
NSString *strurl=[NSString stringWithFormat:#"http://inst.niftysol.com/app/webroot/webservices/test.php?said=%d&stepid=%#", appdel.idPARENTID,s_id_live];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:strurl]];
[request setShouldContinueWhenAppEntersBackground:YES];
[request setData:imagedata withFileName:[NSString stringWithFormat:#"%d.jpeg",i+1] andContentType:#"image/jpeg" forKey:[NSString stringWithFormat:#"userfile%d",i+1]];
request.tag = i;
[[self networkQueue] addOperation:request];
}
[[self networkQueue] go];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
if ([[self networkQueue] requestsCount] == 0) {
[self setNetworkQueue:nil];
}
//... Handle success
NSLog(#"Individual Request finished");
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
if ([[self networkQueue] requestsCount] == 0) {
[self setNetworkQueue:nil];
}
NSLog(#"Individual Request failed");
}
- (void)queueFinished:(ASINetworkQueue *)queue
{
if ([[self networkQueue] requestsCount] == 0) {
[self setNetworkQueue:nil];
}
NSLog(#"Whole Queue finished");
}
Hope this helps. Don't hesitate to message if you need more help.

How to get thumbnails of a video saved in document directory

I saved the captured video in document directory as shown below and now I want to display the thumbnails and play the same video.How to do this ?
- (void) imagePickerController: (UIImagePickerController *) picker didFinishPickingMediaWithInfo: (NSDictionary *) info
{
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
[self dismissModalViewControllerAnimated:NO];
// Handle a movie capture
if (CFStringCompare ((__bridge_retained CFStringRef) mediaType, kUTTypeMovie, 0) == kCFCompareEqualTo)
{
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *movieName = [NSString stringWithFormat:#"%#.mov",[CoreDataFunctions getNameForVideoForDate:[CalendarFunctions getCurrentDateString]]];
NSString *moviePath = [documentsDir stringByAppendingPathComponent:movieName];
NSURL * movieURL = [info valueForKey:UIImagePickerControllerMediaURL];
NSData * movieData = [NSData dataWithContentsOfURL:movieURL];
NSLog(#"%#",moviePath);
if([movieData writeToFile:moviePath atomically:NO])
{
if(![CoreDataFunctions saveVideoInfoInDatabaseForDate:[CalendarFunctions getCurrentDateString]])
{
NSLog(#"Video was saved in doucment directory but could not be saved in core data");
}
}
else
{
NSLog(#"Video could not be saved to the document directry");
}
}
}
Get videos from doc dir like this
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSError * error;
NSArray *directoryContents = [[NSFileManager defaultManager]
contentsOfDirectoryAtPath:documentsDirectory error:&error];
//Take all images in NSMutableArray
NSMutableArray *arrVideoImages = [[NSMutableArray alloc]init];
for(NSString *strFile in directoryContents)
{
NSString *strVideoPath = [NSString stringWithFormat:#"%#/%#",documentsDirectory,strFile];
UIImage *img = [self getThumbNail:strVideoPath];
[arrVideoImages addObject:img];
}
Also add this method:
-(UIImage *)getThumbNail:(NSString)stringPath
{
NSURL *videoURL = [NSURL fileURLWithPath:stringPath];
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];
UIImage *thumbnail = [player thumbnailImageAtTime:1.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
//Player autoplays audio on init
[player stop];
[player release];
return thumbnail;
}

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];