Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
TWTHasselhoffImageProtocol
//
// TWTHasselhoffImageProtocol.h
// TestURLProtocol
//
// Created by Josh Johnson on 5/9/14.
// Copyright (c) 2014 Two Toasters, LLC. All rights reserved.
//
@import Foundation;
@interface TWTHasselhoffImageProtocol : NSURLProtocol
@end
//
// TWTHasselhoffImageProtocol.m
// TestURLProtocol
//
// Created by Josh Johnson on 5/9/14.
// Copyright (c) 2014 Two Toasters, LLC. All rights reserved.
//
#import "TWTHasselhoffImageProtocol.h"
@implementation TWTHasselhoffImageProtocol
+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
NSSet *validContentTypes = [NSSet setWithArray:@[ @"image/png",
@"image/jpg",
@"image/jpeg" ]];
return [validContentTypes containsObject:request.allHTTPHeaderFields[@"Content-Type"]];
}
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
{
return request;
}
- (NSCachedURLResponse *)cachedResponse
{
return nil;
}
- (void)startLoading
{
id <NSURLProtocolClient> client = self.client;
NSURLRequest *request = self.request;
NSDictionary *headers = @{ @"Content-Type": @"image/jpeg" };
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"David_Hasselhoff.jpeg"], 1.0);
NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:request.URL
statusCode:200
HTTPVersion:@"HTTP/1.1"
headerFields:headers];
[client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
[client URLProtocol:self didLoadData:imageData];
[client URLProtocolDidFinishLoading:self];
}
- (void)stopLoading
{
// Must be implemented
}
@end

suncry commented May 30, 2016

good

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment