I'm creating a NSMutableURLRequest
using this code:
NSString *urlString = @"http://192.168.1.111/api";
NSURL *url = [NSURL URLWithString:urlString];
NSString *postBody = [NSString stringWithFormat:@"param=%@", param];
NSData *postBodyData = [postBody dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postBodyLength = [@( postBodyData.length ) stringValue];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
request.URL = url;
request.HTTPMethod = @"POST";
request.HTTPBody = postBodyData;
request.cachePolicy = NSURLRequestUseProtocolCachePolicy;
[request setValue:postBodyLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
and this code to make the request:
NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
if (cachedResponse && cachedResponse.data.length > 0) {
NSError *serializationError = nil;
id cachedResponseData = [NSJSONSerialization JSONObjectWithData:cachedResponse.data options:0 error:&serializationError];
if (!serializationError) {
NSLog(@"WEB: %@:%@ cachedResponseData: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), cachedResponseData);
[self showTranslations:cachedResponseData forWords:queryStrings withCallback:completion];
}
} else {
AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
requestOperation.responseSerializer = [AFJSONResponseSerializer serializer];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"WEB: %@:%@ responseObject: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"WEB: %@:%@ error: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), error);
}];
[[NSOperationQueue mainQueue] addOperation:requestOperation];
}
If I first run it with the param
variable equal to "first"
, if goes through the else
block and makes the request. On a second run, it goes through the if
block and retrieves the response data from cache. But if I run it again with the param
variable equal to "second"
, it goes through the if
block again and retrieves from cache the value coresponding with the first request. How can I make it work like it should and realize that's a different request and not take it from cache?