ComDubh
ComDubh

Reputation: 793

Caching problems reading a URL in iOS

I'm developing an iPhone app where I read a bus timetable stored at a URL. The timetable changes frequently, so I want to read it afresh every time, not take a copy from cache. This is the code that I'm using:

   NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:timetable_URL]];
   NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

However, this seems to read a cached copy, so when the timetable changes on the server, it takes a while for the app to pick it up. Can anyone tell me how to force the data to be read from the server? Thanks for any help on this.

Upvotes: 0

Views: 299

Answers (3)

Kevin
Kevin

Reputation: 1506

You can specify the cache policy when creating your NSURLRequest

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:timetable_URL]
                          cachePolicy: NSURLRequestReloadIgnoringLocalCacheData
                        timeoutInterval:30.0];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

Upvotes: 2

RFG
RFG

Reputation: 2902

Try something like:

NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
  cachePolicy:NSURLRequestReloadIgnoringCacheData
  timeoutInterval:timeInterval]
NSURLConnection *urlConnection = [NSURLConnection connectionWithRequest:urlRequest
   delegate:self];

And use:

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
   return nil;
}

Upvotes: 1

ksimons
ksimons

Reputation: 3826

Use the cachePolicy property on NSURLRequest specifying NSURLRequestReloadIgnoringLocalCacheData

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/Reference/Reference.html#//apple_ref/occ/instm/NSURLRequest/cachePolicy

Upvotes: 1

Related Questions