Skip to content

Instantly share code, notes, and snippets.

@cameronehrlich
Last active March 25, 2018 12:08
Show Gist options
  • Select an option

  • Save cameronehrlich/a5dcbccfc00584a15d4e to your computer and use it in GitHub Desktop.

Select an option

Save cameronehrlich/a5dcbccfc00584a15d4e to your computer and use it in GitHub Desktop.
An example of how to get a UIWebView to display a non-mobile version of a GitHub repository by spoofing the UserAgent.
@interface PLViewController ()
@property (strong, nonatomic) IBOutlet UIWebView *webView;
@end
@implementation PLViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// So I can do the zoomage
[self.webView setUserInteractionEnabled:YES];
// So I can see the whole page to start, ESPECIALLY so I can see the README off the bat
[self.webView setScalesPageToFit:YES];
// This is the "UserAgent" sent by the iPad version of Safari.app, You can probably play around with this.
NSString *iPadUserAgent = @"Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X)"
"AppleWebKit/536.26 (KHTML, like Gecko)"
"Version/6.0 Mobile/10A5355d Safari/8536.25";
/*
I first tried setting the "User-Agent" and "UserAgent" HTTP headers in a NSMutableURLRequest, but that didn't work.
I found some people talking about having to register the "UserAgent" the NSUserDefaults.
This did work, but with some minor caveats.
Users were having to register the default in the +initialize method of their app delegate in order to avoid seeing this console logged error:
ERROR: unable to get the receiver data from the DB!
After a quick search, I found that this had something to do with the cachePolicy.
Below you will see that by setting the cachPolicy to NSURLCacheStorageNotAllowed, you can swap out the UserAgent to be whatever, whenever!
*/
// Register the UserAgent User Default
[[NSUserDefaults standardUserDefaults] registerDefaults:@{ @"UserAgent" : iPadUserAgent }];
// URL of Github Repo to view non-mobile
NSURL *url = [NSURL URLWithString:@"https://github.com/AFNetworking/AFNetworking"];
// I didn't test all the cachePolicy options, but I know this works.
// 60 is the default timeoutInterval, but in my fiddling it didn't make a difference.
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:60];
// Load that puppy
[self.webView loadRequest:urlRequest];
/*
Hopefully this helps get the feature I requested.
Again, thanks for Polife, I really enjoy it!
~ @cameronehrlich
*/
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment