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 iPhone SDK's UIWebView control the way it is, say, for an embedded IE browser in a Windows app?
Actually adding any header field to the NSURLRequest argument in shouldStartLoadWithRequest seems to work, because the request responds to setValue:ForHTTPHeaderField - but it doesn't actually work - the request is sent out without the header.
So I used this workaround in shouldStartLoadWithRequest which just copies the given request to a new mutable request, and re-loads it. This does in fact modify the header which is sent out.
Unfortunately, this still doesn't allow overriding the user-agent http header, which is apparently overwritten by Apple. I guess for overriding it you would have to manage a NSURLConnection by yourself.
The only problem I have found was change user agent only
Taking everything this is how it was solved for me:
Thanks Everyone.
By pooling the answer by Louis St-Amour and the
NSUserDefaults+UnRegisterDefaults
category from this question/answer, you can use the following methods to start and stop user-agent spoofing at any time while your app is running:I faced the same question. I want to add some info to the user-agent, also need to keep the original user-agent of webview. I solved it by using the code below:
Use it before you instancing webview.
Modern Swift
Here's a suggestion for Swift 3+ projects from StackOverflow users PassKit and Kheldar:
Source: https://stackoverflow.com/a/27330998/128579
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.
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. ;-)