Skip to content

Instantly share code, notes, and snippets.

@karajanyp
Forked from dtrauger/ios-custom-url-protocol
Created November 18, 2018 05:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karajanyp/ec0060401a1e961edc3721d856d033f7 to your computer and use it in GitHub Desktop.
Save karajanyp/ec0060401a1e961edc3721d856d033f7 to your computer and use it in GitHub Desktop.
Custom URL Protocol to Globally Modify User Agent for URL Requests
@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