简体   繁体   中英

write url contents into a string using stringWithContentsOfURL cache

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM