Reading downloaded file objective-c - iphone

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!

Related

Downloading a File with AFNetworking

Trying to write a method for my iPhone program that given a URL address to a file, it would download to the iOS App's Documents Directory.
Following AFNetowrking's Documentation, it seems to work fine except that the filename is always some garbage.
I'm using Xcode 5 with AFNetworking 2.0 added to my project. Here's the code that I have so far:
//#import "AFURLSessionManager.h"
//On load (or wherever):
[self downloadFile:#"http://www.irs.gov/pub/irs-pdf/fw4.pdf"];
-(void)downloadFile:(NSString *)UrlAddress
{ NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:UrlAddress];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response)
{
NSURL *documentsDirectoryPath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]];
return [documentsDirectoryPath URLByAppendingPathComponent:[targetPath lastPathComponent]];
}
completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error)
{
NSLog(#"File downloaded to: %#", filePath);
}];
[downloadTask resume];
}
The end result is that the file is successfully downloaded to my documents directory, but with a garbled name:
File downloaded to: file:///Users/myname/Library/Application%20Support/iPhone%20Simulator/7.0/Applications/25188DCA-4277-488E-B08A-4BEC83E59194/Documents/CFNetworkDownload_60NWIf.tmp
The end result I'm expecting:
File downloaded to: file:///Users/myname/Library/Application%20Support/iPhone%20Simulator/7.0/Applications/25188DCA-4277-488E-B08A-4BEC83E59194/Documents/fw4.pdf
I used cocoapods to add AFNetworking to my project:
pod 'AFNetworking', "~> 2.0"
Lastly, what do I need to do to get the progress of the download?
This is the answer I was able to create:
-(void)downloadFile:(NSString *)UrlAddress
{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:UrlAddress]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSString *pdfName = #"The_PDF_Name_I_Want.pdf";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:pdfName];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Successfully downloaded file to %#", path);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
NSLog(#"Download = %f", (float)totalBytesRead / totalBytesExpectedToRead);
}];
[operation start];
}
I am open to improvements or suggestions :)
Simply you can replace this line:
return [documentsDirectoryPath URLByAppendingPathComponent:[targetPath lastPathComponent]];
with:
return [documentsDirectoryPath URLByAppendingPathComponent:#"fw4.pdf"];
since [targetPath lastPathComponent] returns something like CFNetworkDownload_60NWIf.tmp

Convert ImagePath in DocumentDirectory to NSURL Iphone

I am using following code
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSURL *myUrl = [[NSURL alloc] initWithString:self.selectedRing.ringThumbNailImagePath];
[Utilities responseDataFromURL:myUrl completionBlock:^(NSData *fileData, NSError *err)
{
if (err != nil)
{
[self.indicator stopAnimating];
[Utilities errorDisplay:#""];
}
else
{
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"Test.igo"];
NSLog(#"FilePath: %#", filePath);
if ([fileData writeToFile:filePath atomically:YES])
{
CGRect rect = CGRectMake(0 ,0 , 0, 0);
NSURL *igImageHookFile = [[NSURL alloc] initWithString:[[NSString alloc] initWithFormat:#"file://%#", filePath]];
NSLog(#"JPG path %#", filePath);
filePath is
Users/umar/Library/Application Support/iPhone Simulator/6.1/Applications/B45223CF-B437-4617-A02D-DCA91C965A5A/Documents/Test.igo
however i get Nil igImageHookFile NSURL. What is wrong?
Use fileURLWithPath for converting your Path of Document Directory to NSURL like this in piece of code:
NSURL *myImagePath = [NSURL fileURLWithPath:filePath]; //here filePath is your document directory full path with extantionm
For Example:
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"Test.igo"];
NSLog(#"FilePath: %#", filePath);
if ([fileData writeToFile:filePath atomically:YES])
{
CGRect rect = CGRectMake(0 ,0 , 0, 0);
NSURL *igImageHookFile = [NSURL fileURLWithPath:filePath];
NSLog(#"URL from path %#", igImageHookFile);
OUTPUT of path URL something like this:-
file://localhost/Users/umar/Library/Application Support/iPhone Simulator/6.1/Applications/B45223CF-B437-4617-A02D-DCA91C965A5A/Documents/Test.igo
Try this:
NSURL *url = [NSURL URLWithString:[Request stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
Hope it Helps!!

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