ASIHTTP Request cancelled error in iphone sdk - iphone

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.

Related

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!

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

Downloading plist with ASIHTTPRequest works only partially

I have a game where there are different categories to play with. These categories are basically plist files. So, if in the future, I want to add plists, the user should be able to download a plist and play new levels. So what I am aiming for is:
Download .plist from URL
Save .plist file in documents directory on iphone (forever)
use .plist
Here is what I did and it works (console logs "finished !!"), but if I check whether the file is in the documents directory, there is no response (the boolean fileExists stays NO).
-(void)startGame:(id)sender{
NSArray *categoriesArray = [[GameStateSingleton sharedMySingleton] categoriesArray];
NSString *category = [NSString stringWithFormat:[categoriesArray objectAtIndex:[sender tag]]];
NSString *thePath = [mainPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.plist",category]];
NSDictionary *categoryPlist = [NSDictionary dictionaryWithContentsOfFile:thePath];
if(categoryPlist != nil){
[[GameStateSingleton sharedMySingleton]setCurrentCategory:category];
[[GameStateSingleton sharedMySingleton]updateHexCountAndInitalTime];
[[CCDirector sharedDirector]replaceScene:[CCTransitionFade transitionWithDuration:TRANSITIONDURATION scene:[LevelSets scene]]];
}
else{
[self plistForCategory:category];
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *myCategory= [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.plist",category]];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:myCategory];
if(fileExists == YES){
[[GameStateSingleton sharedMySingleton]setCurrentCategory:category];
[[GameStateSingleton sharedMySingleton]updateHexCountAndInitalTime];
[[CCDirector sharedDirector]replaceScene:[CCTransitionFade transitionWithDuration:TRANSITIONDURATION scene:[LevelSets scene]]];
NSLog(#"category exists now");
}
}
}
-(void)plistForCategory:(NSString*)category
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSURL *url = [NSURL URLWithString:[ NSString stringWithFormat:#"http://www.tinycles.com/wannaplay/plists/%#.plist",category]];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadDestinationPath:documentsDirectory];
[request setDelegate:self];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSLog(#"finished !!");
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
// Download failed. This is why.
NSError *error = [request error];
NSLog(#"%#", error);
}
Maybe the problem is because you're starting an async request, so if the request has not finished, your if(fileExist==YES) still returns NO; i suggest you in this case to start a sync request:
- (IBAction)startRequest:(id)sender
{
NSURL *url = [NSURL URLWithString:LINK_TO_PLIST];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadDestinationPath:DOC_PATH];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
//start your game after the file is downloaded
}
}

How save images in home directory?

I am making an application in which i have use Json parsing. With the help of json parsing i get photo url which is saved in string. To show images in my cell i use this code
NSString *strURL=[NSString stringWithFormat:#"%#", [list_photo objectAtIndex:indexPath.row]];
NSData *imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: strURL]];
CGRect myImage =CGRectMake(13,5,50,50);
UIImageView *imageView = [[UIImageView alloc] initWithFrame:myImage];
[imageView setImage:[UIImage imageWithData: imageData]];
[cell addSubview:imageView];
Now prblem is that when i go back or forword then i have wait for few second to come back on same view. Now i want that i when application is used first tme then i wait for that screen otherwise get images from home directory. How i save these image in my home directory? How access from home directory?
You can save an image in the default documents directory as follows using the imageData;
// Accessing the documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"myImage.png"];
//Writing the image file
[imageData writeToFile:savedImagePath atomically:NO];
You can use this to write a file to your Documents Folder
+(BOOL) downloadFileFromURL:(NSString *) url withLocalName:(NSString*) localName
{
//Get the local file and it's size.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:localName];
NSError *error;
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:finalPath error:&error];
NSAssert (error == nil, ([NSString stringWithFormat:#"Error: %#", error]));
if (error) return NO;
int localFileSize = [[fileAttributes objectForKey:NSFileSize] intValue];
//Prepare a request for the desired resource.
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"HEAD"];
//Send the request for just the HTTP header.
NSURLResponse *response;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSAssert (error == nil, ([NSString stringWithFormat:#"Error: %#", error]));
if (error) return NO;
//Check the response code
int status = 404;
if ([response respondsToSelector:#selector(statusCode)])
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response;
status = [httpResponse statusCode];
}
if (status != 200)
{
//file not found
return NO;
}
else
{
//file found
}
//Get the expected file size of the downloaded file
int remoteFileSize = [response expectedContentLength];
//If the file isn't already downloaded, download it.
if (localFileSize != remoteFileSize || (localFileSize == 0))
{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
[[NSFileManager defaultManager] createFileAtPath:finalPath contents:data attributes:nil];
return YES;
}
//here we may wish to check the dates or the file contents to ensure they are the same file.
//The file is already downloaded
return YES;
}
and this to read:
+(UIImage*) fileAtLocation:(NSString*) docLocation
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:docLocation];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
[[NSFileManager defaultManager] createFileAtPath:finalPath contents:data attributes:nil];
NSData *databuffer = [[NSFileManager defaultManager] contentsAtPath:finalPath];
UIImage *image = [UIImage imageWithData:databuffer];
return image;
}

Save the The Stream From URL

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");
}
}
}