3

I have a NSURLConnection which I am calling every time -(void)viewWillAppear:animated is called (that's only for now, it's just for testing)

I am doing it like this

receivedData = [[NSMutableData data] retain];
NSString *urlString = @"<URL hidden>";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30.0];
[NSURLConnection connectionWithRequest:request delegate:self];

Then I have these three delegate methods:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [receivedData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSString *returnString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
    usersPhotos = [[NSMutableArray alloc] initWithArray:[[returnString JSONValue] objectForKey:@"data"]];
    [self loadAnnotations];

    NSLog(@"%@", returnString);

    [returnString release];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [self loadAnnotations];
}

Even though I am sure the returnStringshould change (I can visit the site in urlString and confirm it has changed) it is always the same.

It is as if it reuses the data that it retrieves from the first connection.

Does anyone know why this is?

simonbs
  • 7,543
  • 12
  • 64
  • 112

2 Answers2

6

it should be your cache policy, i will update in a second with the correct info.


UPDATE

Try setting your cahce policy to: cachePolicy:NSURLRequestReloadIgnoringCacheData

It should be:

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0];
Nicolas S
  • 5,329
  • 3
  • 27
  • 36
  • That did the trick! Thank you very much! I have been pulling my hair out for hours. I should've have figured that out :-) Thank you. – simonbs Jun 20 '11 at 14:33
  • +1. NSURLRequestReturnCacheDataElseLoad means "return cached data, or if there is no cache data, return data from the source". So the only time the data was from your source was on first load, and then it simply used cached data for the rest. – thomashw Jun 20 '11 at 14:35
  • Yes, that's very smart - I don't know why I even used that in the first place. – simonbs Jun 20 '11 at 14:36
0

You need to empty your buffer if you're re-using it.

Add this method:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{   
    [receivedData setLength:0];
}
thomashw
  • 946
  • 4
  • 7
  • if what you say is necessary, wouldnt the actual code just concatenate the recieved string angain and again? `[receivedData appendData:data];` – Nicolas S Jun 20 '11 at 14:26
  • Whoops - I was completely wrong. I assumed the buffer was an instance variable. Didn't read the question thoroughly. – thomashw Jun 20 '11 at 14:34