Ios – Change User Agent in UIWebView


I have a business need to be able to customize the UserAgent for an embedded UIWebView. (For instance, I'd like the server to respond differently if, say, a user is using one version of the app versus another.)

Is it possible to customize the UserAgent in the existing UIWebView control the way it is, say, for an embedded IE browser in a Windows app?

Best Solution

Modern Swift

Here's a suggestion for Swift 3+ projects from StackOverflow users PassKit and Kheldar:

UserDefaults.standard.register(defaults: ["UserAgent" : "Custom Agent"])


Earlier Objective-C Answer

With iOS 5 changes, I recommend the following approach, originally from this StackOverflow question: UIWebView iOS5 changing user-agent as pointed out in an answer below. In comments on that page, it appears to work in 4.3 and earlier also.

Change the "UserAgent" default value by running this code once when your app starts:

NSDictionary *dictionary = @{@"UserAgent": @"Your user agent"};
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
[[NSUserDefaults standardUserDefaults] synchronize];

See previous edits on this post if you need methods that work in versions of iOS before 4.3/5.0. Note that because of the extensive edits, the following comments / other answers on this page may not make sense. This is a four year old question, after all. ;-)

Related Question