Search code examples
iphoneiosipadnetwork-programmingmknetworkengine

How to disable caching in MKNetworkKit or MKNetworkEngine?


I'm trying to use MKNetworkEngine but the headers talk about caching. This is totally bad for my app which needs to download currency exchange rate JSON files and caching is a no-go.

Is there a way to turn caching off for the whole MKNetworkEngine instance?


Solution

  • First things first: Are you really sure about your caching use case? Most of those stock providing web services set their Cache-Pragma/ETags headers to a reasonable value. If they do so, MKNetworkKit will do the right thing and will only respond to your code with a cache hit, if this is valid for your request.

    Nontheless you can control the utilization of the cache via two methods. Right from MKNetworkEngine.h:

        /*!
     *  @abstract Enqueues your operation into the shared queue.
     *  
     *  @discussion
     *  The operation you created is enqueued to the shared queue. 
     *  When forceReload is NO, this method behaves like enqueueOperation:
     *  When forceReload is YES, No cached data will be returned even if cached data is available.
     *  @seealso
     *  enqueueOperation:
     */
    -(void) enqueueOperation:(MKNetworkOperation*) operation forceReload:(BOOL) forceReload;
    

    Calling enqeueOperation:forceReload: with forceReload set to YES will do the trick. Like so:

    -(MKNetworkOperation *)myNetworkOperation onCompletion:(MYComplectionBlock)completionBlock onError:(MKNKErrorBlock)errorBlock {
    
        MKNetworkOperation *op = [self operationWithPath:kURLPath params:nil httpMethod:@"GET" ssl:NO];
        [op onCompletion:^(MKNetworkOperation *completedOperation) {
            // handle the response
            completionBlock(...)
        } onError:^(NSError *error) {
            errorBlock(error);
        }];
    
        [self enqueueOperation:op forceReload:YES];
        return op;  
    }
    

    Further more you can empty the cache explicitly (beware that means emptying the cache for all your requests) with a call to [self emptyCache] just before [self enqueueOperation:op] inside of your MKNetworkEngine subclass.

    -(MKNetworkOperation *)myNetworkOperation onCompletion:(MYComplectionBlock)completionBlock onError:(MKNKErrorBlock)errorBlock {
    
        MKNetworkOperation *op = [self operationWithPath:kURLPath params:nil httpMethod:@"GET" ssl:NO];
        [op onCompletion:^(MKNetworkOperation *completedOperation) {
            // handle the response
            completionBlock(...)
        } onError:^(NSError *error) {
            errorBlock(error);
        }];
    
        [self emptyCache];
        [self enqueueOperation:op];
        return op;  
    }