NSMutableURLRequest returns old values even cachePolicy is NSURLCacheStorageNotAllowed

663 Views Asked by At

Im using codes posted here:
connection release method in connectionDidFinishLoading, causes error

now first execute returns didFail log. second execute; returns old response data. albeit my (localhost) server is totally offline. and cachePolicy is NSURLCacheStorageNotAllowed (check the code on the link I posted above)

 NSMutableURLRequest *request=
[NSMutableURLRequest requestWithURL:url 
cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:3.0f];

the response data seems cached somewhere and still exists.

but if I use NSURLRequestReloadIgnoringLocalAndRemoteCacheData //which is commented as -not implemented-

not returns old cache.

but if so what is the difference between:
NSURLRequestReloadIgnoringLocalAndRemoteCacheData
and
NSURLCacheStorageNotAllowed

what shall I do ?

2

There are 2 best solutions below

1
On

Try This

NSString *Post = [[NSString alloc] initWithFormat:@"Post Parameters"]; NSURL *Url = [NSURL URLWithString:@"Url"];

    NSData *PostData = [Post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    NSString *postLength = [NSString stringWithFormat:@"%d", [PostData length]];

    NSMutableURLRequest *Request = [[NSMutableURLRequest alloc] init];
    [Request setURL:Url];
    [Request setHTTPMethod:@"POST"];
    [Request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [Request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [Request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [Request setHTTPBody:PostData];
  NSError *error;
    NSURLResponse *response;

    NSData *Result = [NSURLConnection sendSynchronousRequest:Request returningResponse:&response error:&error];
    if (!Result)
    {
        NSLog(@"Error");
    }
    else
    {
       //Parse the result
    }
0
On

NSURLCacheStorageNotAllowed refers to NSCachedURLResponse and is an value of enum NSURLCacheStoragePolicy. Since the cache policy of NSMutableURLRequest is also an enum (NSURLRequestCachePolicy) you just pass wrong int to the static method creating NSMutableURLRequest. In this case NSURLCacheStorageNotAllowed is just 2 which equals to NSURLRequestReturnCacheDataElseLoad - and that is why you get old data.