Copy XML file from Server to iphone? - iphone

I want to copy the xml file from server to save it to locally, because if I will send request to server again and again, it will take time, so I want to copy the xml to local resources whenever app starts, then parse the local xml,
how can I do it?

First of all you need to download the file:
NSURL *url = [NSURL URLWithString:FILEURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection connectionWithRequest:request delegate:self];
then add in the h file:
NSMutableData *receivedData;
and in the m file:
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
if (receivedData)
{
[receivedData appendData:data];
}
else
{
receivedData = [[NSMutableData alloc] initWithData:data];
}
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection
{
//saving your data in the local
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fullName = [NSString stringWithFormat:#"xmlfile.xml"];
NSString *fullFilePath = [NSString stringWithFormat:#"%#/%#",docDir,fullName];
[receivedData writeToFile:fullFilePath atomically:YES];
}
edit:
get the file from local-
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fullName = [NSString stringWithFormat:#"xmlfile.xml"];
NSString *fullFilePath = [NSString stringWithFormat:#"%#/%#",docDir,fullName];
NSData *myData = [NSData dataWithContentsOfFile:filePath];
now you can take the NSData when parse it,there are a lot of examples in the site.

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

Download file from URL and place it in Resource folder in iPhone

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.

downloading using NSURLConnection not downloading anything?

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

NSMutableData Save to a File

I downloaed the file using code shown below. Then i am trying to save NSMutableData variable to file, however, the file is not created. What am i doing wrong? Do i need to convert NSMutableData into NSString?
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)_response {
response = [_response retain];
if([response expectedContentLength] < 1) {
data = [[NSMutableData alloc] init];
}
else {
data = [[NSMutableData dataWithCapacity:[response expectedContentLength]] retain];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)_data {
[data appendData:_data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"file" ofType:#"txt"];
NSLog(#"saved: %#", filePath);
[data writeToFile:filePath atomically:YES];
NSLog(#"downloaded file: %#", data); //all i see in log is some encoded data here
}
You can’t write inside your app’s bundle. You’ll need to save it somewhere else, like your app’s Documents directory:
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"file.txt"];
[data writeToFile:filePath atomically:YES];

download multiple files on iphone

i want to download file(s) from web server.
Scenario:
As user will select row (file name- user can select 1 or more files to download) and and press download, i am getting URL for each file(all have different URL) and storing into pathArray.
and doing following
-(void)downloadFile {
for (int i = 0; i<[pathArray count]; i++) {
NSURL *fileURL = [NSURL fileURLWithPath:[pathArray objectAtIndex:i]];
NSString *ResultURL = [fileURL absoluteString];
NSURL *url = [[NSURL alloc] initWithString:ResultURL];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL: url
cachePolicy: NSURLRequestReloadIgnoringCacheData timeoutInterval: 60.0];
conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
if (conn) {
NSLog(#"*************CONNECTED************");
webData = [[NSMutableData data] retain];
NSLog(#"weblength : %d : ", [webData length]);
downloadTag = YES;
} else {
NSLog(#"*************Connection NOT DONE************");
downloadTag=NO;
}
}
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"*************Try to receive data************");
[webData appendData:data];
NSLog(#"weblength : %d : ", [webData length]);
NSLog(#"*************Data Received an append too ***********");
if (downloadTag == YES) {
paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
self.documentsDir = [[paths objectAtIndex:0]stringByAppendingPathComponent:#"NewResult.zip" ];
[[NSFileManager defaultManager] createFileAtPath:documentsDir contents:nil attributes:nil];
NSFileHandle *file1 = [NSFileHandle fileHandleForUpdatingAtPath: documentsDir];
[file1 writeData: webData];
NSLog(#"Webdata : %d",[webData length]);
[file1 closeFile];
}
}
if i am not using for loop i.e only one file download then it work fine but not with for loop....its really important for me to solve this issue.
thank you very much
take a look at ASIHTTPRequest, it has a nice queue for downloading and monitoring progress http://allseeing-i.com/ASIHTTPRequest/How-to-use
You're using asynchronous downloads, but the delegate for each download item is the same object, causing all of the downloaded data to get appended to the same file. The way I do it is to have a small Object (DownloadQueueItem) that is the delegate for a single download. When you download another file, you create a new DownloadQueueItem and it handles everything.
Edit:
Q: instead of %i putting by my self i am searching is there any way to create new file every time like if ""NewResult.zip" is exist then create "NewResult1.zip" and so on
A: You could do something like this:
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filename = #"NewResult%#.zip";
for (int i = 0; ; i++) {
NSString *filename = NULL;
if (i == 0) {
filename = [NSString stringWithFormat:filename, #""];
}
else {
filename = [NSString stringWithFormat:filename, [NSString stringWithFormat:#"%i", i]];
}
if (![[NSFileManager defaultManager] fileExistsAtPath:filename]) {
// Save file.
break;
}
}