Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

connection:willCacheResponse will never get called

Tags:

xcode

iphone

I'm working on an iPhone App which involves downloading data from a web server. All things are working fine except the method connection:willCacheResponse: will never get called. But others like connection:didReceiveResponse:, connection:didReceiveData:, connection:didFailWithError:, connectionDidFinishLoading: all working fine. I made the connection like following:

- (void)makeConnection
{
    NSURL *url = [NSURL URLWithString:@"http://www.abc.com"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60];
    [request setHTTPMethod:@"POST"];
    NSString *postString = [NSString stringWithFormat:@"%@", string];
    [request setValue:[NSString stringWithFormat:@"%d", [postString length]] forHTTPHeaderField:@"Content-length"];
    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
    NSCachedURLResponse *newCachedResponse = cachedResponse;
    NSDictionary *newCachedResponseUserInfo = [NSDictionary dictionaryWithObject:[NSDate date] forKey:@"Cached Date"];
    newCachedResponse = [[NSCachedURLResponse alloc] initWithResponse:[cachedResponse response] data:[cachedResponse data] userInfo:newCachedResponseUserInfo storagePolicy:[cachedResponse storagePolicy]];

    return newCachedResponse;
}

I also try to change the policy to NSURLRequestUseProtocolCachePolicy, but nothing help. Also tried to put a break point in

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse

but nothing happened. Am I missing something? Thank you in advance.

like image 218
user1139921 Avatar asked Jul 23 '26 16:07

user1139921


1 Answers

connection:willCacheResponse: is only called if the response contains a Cache-Control header, according to Apple’s documentation:

The delegate receives connection:willCacheResponse: messages only for protocols that support caching.

like image 119
Manish Agrawal Avatar answered Jul 26 '26 04:07

Manish Agrawal