Search code examples
iphonexcodeios5xcode4

Adding a timestamp to NSURL


I have a textview that downloads the text from a .txt on my server. The only problem is that it will only do that once-- no matter if I update the .txt file or not, the text will not change.

Here is the code for the textview:

- (void)viewDidLoad

{NSError *error = nil;
NSURL *myurl = [NSURL URLWithString:@"http://www.myserver.com/test.txt"];
NSString *mystring = [NSString stringWithContentsOfURL:myurl encoding:NSUTF8StringEncoding error:&error]; 
newtext.text = mystring;
}

Can't seem to figure out how to make it check the server each time the app runs (and not just cache what it found the first time). This happens in the simulator and on a real iphone as well.

Thanks for any help!


Solution

  • I do not believe you can set the cache policy with the convenience method stringWithContentsOfURL. Someone correct me if I am wrong.

    The good news is that this is pretty simple to fix. Simply create your own request and set the cache policy to NSURLRequestReloadIgnoringLocalCacheData.

    NSURL *myurl = [NSURL URLWithString:@"http://www.myserver.com/test.txt"];
    NSURLRequest *request = [NSURLRequest requestWithURL:myurl
                                             cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                         timeoutInterval:60.0];
    
    NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request 
                                                                 delegate:self];
    

    Then set the text view in the delegate. At the end of the day, this is what the convenience method is doing anyway.