Created
November 17, 2014 15:19
-
-
Save dtrauger/793582ea90c4ff8da10c to your computer and use it in GitHub Desktop.
Custom URL Protocol to Globally Modify User Agent for URL Requests
This file contains 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
@interface CustomBrowserURLProtocol : NSURLProtocol | |
@end | |
@interface CustomBrowserURLProtocol () | |
@property (nonatomic, strong) NSURLConnection *connection; | |
@end | |
@implementation CustomBrowserURLProtocol | |
+ (BOOL)canInitWithRequest:(NSURLRequest *)request | |
{ | |
if ([NSURLProtocol propertyForKey:@"UserAgentSet" inRequest:request] != nil) | |
return NO; | |
return YES; | |
} | |
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request | |
{ | |
return request; | |
} | |
- (void)startLoading | |
{ | |
NSMutableURLRequest *newRequest = [self.request mutableCopy]; | |
NSBundle *bundle = [NSBundle bundleForClass:[self class]]; | |
NSString *appName = [bundle objectForInfoDictionaryKey:@"CFBundleDisplayName"]; | |
NSString *bundleIdentifier = [bundle objectForInfoDictionaryKey:@"CFBundleIdentifier"]; | |
NSString *publicVersionNumber = [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"]; | |
NSString *privateBuildNumber = [bundle objectForInfoDictionaryKey:@"CFBundleVersion"]; | |
NSString *osVersion = [[UIDevice currentDevice] systemVersion]; | |
NSString *updatedUserAgent = [NSString stringWithFormat:@"%@ %@/%@ (iOS %@; %@; build:%@)", [[newRequest allHTTPHeaderFields] objectForKey:@"User-Agent"], appName, publicVersionNumber, osVersion, bundleIdentifier, privateBuildNumber]; | |
[newRequest setValue:updatedUserAgent forHTTPHeaderField:@"User-Agent"]; | |
[NSURLProtocol setProperty:@YES forKey:@"UserAgentSet" inRequest:newRequest]; | |
self.connection = [NSURLConnection connectionWithRequest:newRequest delegate:self]; | |
} | |
- (void)stopLoading | |
{ | |
[self.connection cancel]; | |
} | |
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data | |
{ | |
[self.client URLProtocol:self didLoadData:data]; | |
} | |
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error | |
{ | |
[self.client URLProtocol:self didFailWithError:error]; | |
self.connection = nil; | |
} | |
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response | |
{ | |
[self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed]; | |
} | |
- (void)connectionDidFinishLoading:(NSURLConnection *)connection | |
{ | |
[self.client URLProtocolDidFinishLoading:self]; | |
self.connection = nil; | |
} | |
@end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment