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];
}
Related
I have a pdf file from server.
Then I need to load the file to NSDocument directory path and its working fine, but i want to show UIProgressView for store each bytes. How to do this , please help me
Thanks in Advance
I tried to store like this:
NSError *error;
NSArray *ipaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *idocumentsDir = [ipaths objectAtIndex:0];
NSString *idataPath = [idocumentsDir stringByAppendingPathComponent:#"File"];
NSLog(#"idataPath:%#",idataPath);
//Create folder here
if (![[NSFileManager defaultManager] fileExistsAtPath:idataPath])
{
[[NSFileManager defaultManager] createDirectoryAtPath:idataPath withIntermediateDirectories:NO attributes:nil error:&error];
}
// Image Download here
NSString *fileName = [idataPath stringByAppendingFormat:#"/image.jpg"];
NSLog(#"imagePathDOWNLOAD:%#",fileName);
NSData *pdfData1 = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:[URLArray objectAtIndex:a]]];
[pdfData1 writeToFile:fileName atomically:YES];
You can use NSURLConnection class to implement progress bar:
.h:
NSMutableData *responseData;
NSString *originalFileSize;
NSString *downloadedFileSize;
.m:
- (void)load {
NSURL *myURL = [NSURL URLWithString:#""];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:60];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
responseData = [[NSMutableData alloc] init];
originalFileSize = [response expectedContentLength];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
downloadedFileSize = [responseData length];
progressBar.progress = ([originalFileSize floatValue] / [downloadedFileSize floatValue]);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[responseData release];
[connection release];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Succeeded! Received %d bytes of data",[responseData lengtn]);
}
Let me know for any queries.
I am new to iPhone developer,
How can i download the epub file from url and store it in Resource folder ?
Here is my code snippet,
- (void)viewDidLoad
{
[super viewDidLoad];
fileData = [NSMutableData data];
NSString *file = [NSString stringWithFormat:#"http://www.google.co.in/url?sa=t&rct=j&q=sample%20epub%20filetype%3Aepub&source=web&cd=2&ved=0CFMQFjAB&url=http%3A%2F%2Fdl.dropbox.com%2Fu%2F1177388%2Fflagship_july_4_2010_flying_island_press.epub&ei=i5gHUIOWJI3RrQeGro3YAg&usg=AFQjCNFPKsV-tieF4vKv7BXYmS-QEvd7Uw"];
NSURL *fileURL = [NSURL URLWithString:file];
NSURLRequest *req = [NSURLRequest requestWithURL:fileURL];
NSURLConnection *conn = [NSURLConnection connectionWithRequest:req delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.fileData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.fileData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSArray *dirArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(#"%#", [dirArray objectAtIndex:0]);
NSString *path = [NSString stringWithFormat:#"%#", [dirArray objectAtIndex:0]];
if ([self.fileData writeToFile:path options:NSAtomicWrite error:nil] == NO) {
NSLog(#"writeToFile error");
}
else {
NSLog(#"Written!");
}
}
I am not able to see anything in my NSLog.
There is a problem in creation of file path also while writing. you have not specified any filename in the path. In the below line, I have used file name as "filename.txt". Give some proper name and it will write.
NSString *path = [NSString stringWithFormat:#"%#/filename.txt", [dirArray objectAtIndex:0]];
There is a problem in creating URL also. Do it like this,
NSString *file = [NSString stringWithString:#"http://www.google.co.in/url?sa=t&rct=j&q=sample%20epub%20filetype%3Aepub&source=web&cd=2&ved=0CFMQFjAB&url=http%3A%2F%2Fdl.dropbox.com%2Fu%2F1177388%2Fflagship_july_4_2010_flying_island_press.epub&ei=i5gHUIOWJI3RrQeGro3YAg&usg=AFQjCNFPKsV-tieF4vKv7BXYmS-QEvd7Uw"];
NSURL *fileURL = [NSURL URLWithString:file];
You have created your file data with below line.
fileData = [NSMutableData data];
Make it like below,
fileData = [[NSMutableData alloc]init];
OR
self.fileData = [NSMutableData data];
Here iOS releases filedata before your connection delegate get called.
i am using NSURLConnection to download mp3 data from the server , my code is here
- (IBAction)downloadData:(id)sender
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL *url = [[NSURL alloc] initWithString:#"http://viadj.viastreaming.net/start/psalmsmedia/ondemand/Nin%20snehamethrayo.mp3"];
[request setURL:url];
[url release];
url = nil;
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (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
{
[responseData release];
[connection release];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Succeeded! Received %d bytes of data",[responseData
length]);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileName = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"myFile"];
[responseData writeToFile:fileName atomically:YES];
responseData = nil;
self->imageConnection = nil;
}
am little bit confused about the path given to download. when i click download button i shows "Succeeded! Received 1329 bytes of data" but nothing is downloading. need some help. how will we specify the local path of iPhone to store downloaded data?
- (IBAction)downloadData:(id)sender
{
NSURL *url = [[NSURL alloc] initWithString:#"http://viadj.viastreaming.net/start/psalmsmedia/ondemand/Nin%20snehamethrayo.mp3"];
NSMutableURLRequest *theRequest_to = [NSMutableURLRequest requestWithURL:url];
[url release];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:theRequest_to delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse*)response
{
NSString *filepath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:#"snehamethrayo.mp3"]; // here you can set your filename which you can get from url
[[NSFileManager defaultManager] createFileAtPath:filepath contents:nil attributes:nil];
file = [[NSFileHandle fileHandleForUpdatingAtPath:filepath] retain];// Here file is object of NSFileHandle and its declare in .h File
[file seekToEndOfFile];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[file seekToEndOfFile];
[file writeData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection*)connection
{
[file closeFile];
}
No need for any code change I think.Just put an nslog and see...
NSString *fileName = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"myFile"];
NSLog(#"%#",fileName);
That will list the file location like this
/Users/me/Library/Application Support/iPhone Simulator/5.0/Applications/(your app)/Documents/myFile. ie the downloaded file is in your document folder.
note: don't forget to put the file format ie
NSString *fileName = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"myFile.mp3"];
If someone want to download a file instead of playing it, then what functionality or method will be used for it.
I want to download the file. Provide me some example if u can, or give me some idea about this concept.
Thankyou very much.
Send request following way.
NSURL *url = [NSURL URLWithString:[fileUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setValue:[NSString stringWithFormat:#"bytes=%ld-",0] forHTTPHeaderField:#"Range"];
[theRequest addValue: #"pdf" forHTTPHeaderField:#"Content-Type"];
[theRequest setHTTPMethod:#"POST"];
webData = [[NSMutableData alloc] init];
theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
Implement following methods...
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection )connection
{
/******CODE FOR WRITING FILE*************/
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [paths objectAtIndex:0];
NSString *directoryPath = [documentPath stringByAppendingPathComponent:[MAIN_DIRECTORY stringByAppendingPathComponent:fileDate]];
[[NSFileManager defaultManager] createDirectoryAtPath:directoryPath withIntermediateDirectories:NO attributes:nil error:nil];
[webData writeToFile:fileName atomically:YES];
}
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");
}
}
}