Skip to content

Instantly share code, notes, and snippets.

@EGreg
Created July 10, 2015 21:45
Show Gist options
  • Save EGreg/93aa07e21575f026a214 to your computer and use it in GitHub Desktop.
Save EGreg/93aa07e21575f026a214 to your computer and use it in GitHub Desktop.
Intercepting requests on iOS
#import "FSURLCache.h"
#import <MobileCoreServices/MobileCoreServices.h>
@implementation FSURLCache
- (NSString*) fileMIMEType:(NSString*) file {
NSDictionary *mimeDict = [NSDictionary dictionaryWithObjectsAndKeys:
@"image/png",
@"png",
@"image/jpeg",
@"jpg",
@"image/gif",
@"gif",
@"application/x-javascript",
@"js",
@"text/css",
@"css",
nil];
return [mimeDict objectForKey:[file pathExtension]];
}
-(NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request
{
// Get the path for the request
NSURL *requestUrl = [request URL];
NSString *pathString = [requestUrl relativePath];
if (!([[requestUrl host] isEqualToString: @"groups-cache"])) {
// Use the regular caching mechanism
return [super cachedResponseForRequest:request];
}
// Get the path to the substitute file
NSString *filePath = [NSString stringWithFormat:@"%@/%@%@", [[NSBundle mainBundle] resourcePath], @"www/Groups", pathString];
NSAssert(filePath, @"File %@ didn't exist", filePath);
// Load the data
NSData *data = [NSData dataWithContentsOfFile:filePath];
if(data == nil) return [super cachedResponseForRequest:request];
// Create the cacheable response
NSURLResponse *response = [[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:[self fileMIMEType: pathString] expectedContentLength:[data length] textEncodingName:nil] autorelease];
NSCachedURLResponse *cachedResponse = [[[NSCachedURLResponse alloc] initWithResponse:response data:data] autorelease];
return cachedResponse;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment