3

My code is writing contents of url from an xml file on my web server and stores the contents in a string then write it to a local file in documents directories. Everything is going fine with me when I load it for the first time, after that even when I run this view again it will always get the contents which is already cached on the device and no updates are coming from the web server.

How to enforce it to read the contents from the file on the server at everytime?

NSString * path = @"http://my-domain-name.com/myGlobalFile.xml";
NSString * myStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:path] encoding:NSUTF8StringEncoding error:nil];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
localFilePath = [documentsDirectory stringByAppendingPathComponent:@"myLocalFile.xml"];
[myStr writeToFile:localFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
SalehAlmusallam
  • 118
  • 1
  • 2
  • 7
  • Where in your program do you do above snippet? You may also want to check the error object that writeToFile can return. – onnoweb Oct 26 '11 at 14:19

1 Answers1

2

You could download the string using an NSURLRequest and NSURLConnection (which would actually be a better way of doing things -- asynchronously -- and you can also feedback on progress (http://stackoverflow.com/questions/2267950/how-to-make-an-progress-bar-for-an-nsurlconnection-when-downloading-a-file)).

NSURLRequest gives you much finer control over the caching policy you want to use.

You would set up your NSURLRequest as follows:

NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://my-domain-name.com/myGlobalFile.xml"] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];

You can substitute NSURLRequestReloadIgnoringLocalCacheData with values from http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/Reference/Reference.html (scroll down to "NSURLRequestCachePolicy" if you want to choose a different policy.)

For full documentation of how to finish off this code (along with the necessary delegate methods you will need to implement), see the excellent docs at:

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html

which will talk you through the whole process.

Jonathan Ellis
  • 5,221
  • 2
  • 36
  • 53