Last active
January 29, 2017 10:59
-
-
Save mttrb/6594137 to your computer and use it in GitHub Desktop.
NSURLProtocol subclass that allows downloads to be intercepted.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// BLCURLProtocol.m | |
// URLProtocol | |
// | |
// Created by Matthew Robinson on 17/09/13. | |
// Copyright (c) 2013 Blended Cocoa. All rights reserved. | |
// | |
#import "BLCURLProtocol.h" | |
@interface BLCURLProtocol () | |
@property (strong,nonatomic) NSURLConnection *connection; | |
@end | |
@implementation BLCURLProtocol | |
+ (BOOL)canInitWithRequest:(NSURLRequest *)request { | |
// If the request has the property set then we have already dealt with this request. | |
if ([NSURLProtocol propertyForKey:NSStringFromClass([self class]) inRequest:request]) { | |
return NO; | |
} | |
return YES; | |
} | |
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { | |
return request; | |
} | |
- (void)startLoading { | |
NSLog(@"startLoading"); | |
// Copy the request and a property so we don't deal with this request when it comes through again. | |
NSMutableURLRequest *newRequest = [self.request mutableCopy]; | |
[NSURLProtocol setProperty:@YES forKey:NSStringFromClass([self class]) inRequest:newRequest]; | |
// Create a new NSURLConnection and we will proxy the new request to the original request. | |
self.connection = [NSURLConnection connectionWithRequest:newRequest delegate:self]; | |
} | |
- (void)stopLoading { | |
[self.connection cancel]; | |
} | |
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { | |
NSLog(@"%@", response); | |
[self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed]; | |
} | |
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { | |
NSLog(@"%@", data); | |
[self.client URLProtocol:self didLoadData:data]; | |
} | |
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { | |
NSLog(@"didFailWithError"); | |
[self.client URLProtocol:self didFailWithError:error]; | |
} | |
- (void)connectionDidFinishLoading:(NSURLConnection *)connection { | |
NSLog(@"didFinishLoading"); | |
[self.client URLProtocolDidFinishLoading:self]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment