dzenbot / DZNWebViewController

A simple web browser for iPhone & iPad with similar features than Safari's
https://www.cocoacontrols.com/controls/dznwebviewcontroller
MIT License
1.06k stars 181 forks source link

How to use a custom User Agent? #59

Closed marbetschar closed 8 years ago

marbetschar commented 8 years ago

How may I define a custom user agent used by the DZNWebViewController?

The reason is, I've embedded a Knowledge Base website within my app using the DZNWebViewController. This website has some features which are nice for desktop, but not embedded within an app - so I'd like to hide those website features based on the user agent.

dzenbot commented 8 years ago

Why not using the iPhone/iPad user agent?

marbetschar commented 8 years ago

Because of the reason I've mentioned...?

These website features should only be hidden if the site is embedded in App. If the website is visitted by a regular browser everything can be showed - even in Safari on iPhone.

marbetschar commented 8 years ago

I was able to solve this without touching the code of DZNWebViewController. I've added the following snippet in my application(...didFinishLaunchingWithOptions: ...)

if let bundleName = NSBundle.mainBundle().infoDictionary?["CFBundleName"] as? String,
  let bundleVersion = NSBundle.mainBundle().infoDictionary?["CFBundleShortVersionString"] as? String,
  let defaultUserAgent = UIWebView().stringByEvaluatingJavaScriptFromString("navigator.userAgent"){

    NSUserDefaults.standardUserDefaults().registerDefaults([
      "UserAgent": defaultUserAgent + " \(bundleName)/\(bundleVersion)"
    ])
}
dzenbot commented 8 years ago

You could have used NSURLProtocol too, to append this user agent to either all outgoing requests, or the ones from the in-app browser.