Yuvaraj.M
Yuvaraj.M

Reputation: 9801

How to download file and save in local iphone application?

I have locally saved one xml file and showing the details by using NSXmlParser(Which is stored in Resource folder). But, now i want to download new xml from url(from client side) and need to store that new xml file in local and also need to delete existing one from the application. How can i do this? Any suggestions? There is any sample code/project for reference? Please help me. Thanks for reading my poor english. Thanks is advance.

Upvotes: 1

Views: 1547

Answers (1)

Dhaval Panchal
Dhaval Panchal

Reputation: 2529

although u can delete file from yr resource directory and save new one but the my way is to perform file operation mostly on app diretories like document directory or cache directory.

first u will to save yr xml file from app resource to cache directory then access file from there.And u can also remove file from resource directory ,its no longer needed. any new file available in internet then first remove old one from cache and add new one to cache directory.

whole thing is as follows:-

    //get your cachedirectory path
NSArray *imagepaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachdirectory = [[NSString alloc] initWithString:[imagepaths objectAtIndex:0]];

//first save your file from resource directory to app's cache  directory
NSString * path = [[NSBundle mainBundle] pathForResource:@"fileinresource" ofType:@"xml"];
NSData *filedata = [NSData dataWithContentsOfFile:path];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *savename = [cachdirectory stringByAppendingPathComponent:@"mynewfile.xml"];
[fileManager createFileAtPath:savename contents:filedata attributes:nil];       

//remove file from resource directory
[fileManager removeItemAtPath:path error:nil];

//new file from internet is avilable then do following:first remove old file from cache
[fileManager removeItemAtPath:cachdirectory error:nil];

//save new file from internet
NSData *newfiledata=[NSData dataWithContentsOfURL:[NSURL URLWithString:myxmlurlstringpath]];
[fileManager createFileAtPath:savename contents:newfiledata attributes:nil];        

Upvotes: 2

Related Questions