Question

I am trying to set up a cache, however the method I am using 'as below' is not being accessed by the thread.

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

I am initializing the connection like this, and connectionDidFinishLoading is accessed so I am not sure what I am missing.

- (IBAction)searchRequest:(NSData *)postBodyData
{
    //Set database address
    NSMutableString *databaseURL = [[NSMutableString alloc] initWithString:@"https://127.0.0.1:88"]; 

    NSURL *url = [NSURL URLWithString:databaseURL];

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

    //SynchronousRequest to grab the data, also setting up the cachePolicy
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0]; //if request dose not finish happen within 60 second timeout.

//    NSInputStream *fileStream = [NSInputStream inputStreamWithData:postBodyData];


    [request setHTTPMethod: @"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/octet-stream" forHTTPHeaderField:@"content-type"];
    [request setHTTPBody:postBodyData];

    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];

    if (theConnection) {
        // Create the NSMutableData to hold the received data.
        // receivedData is an instance variable declared elsewhere.
        receivedData = [NSMutableData data];
    } else {
        // Inform the user that the connection failed from the connection:didFailWithError method
    }
}

any help would be appreciated.

Was it helpful?

Solution

connection:willCacheResponse: is only called in cases when the response will be cached. POST requests are not cacheable in most cases. (More details: Is it possible to cache POST methods in HTTP?)

You should probably look at something like MKNetworkKit which handles a lot of this kind of caching, particularly for REST protocols.

You can also look at Drop-in offline caching for UIWebView. You'd have to modify it significantly, but NSURLProtocol can be used to solve this kind of problem. AFCache is currently working to integrate this approach, and is another toolkit to consider. (Read through the comments in the blog post for more background on the issues.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top