- If AppleWebKit appears in the user agent does that mean it’s definitely an apple device?
- 3 Answers 3
- Better way to get AppleWebKit/Mobile/Safari version numbers for User-Agent string?
- Set useragent in WKWebview
- 6 Answers 6
- Alternative
- Tips & Tricks: изменяем User Agent в iPhone
- Change User Agent in UIWebView
- 14 Answers 14
- Modern Swift
- Earlier Objective-C Answer
If AppleWebKit appears in the user agent does that mean it’s definitely an apple device?
User agents can detect the AppleWebKit. This is a browser engine used primarily on Apple devices, BUT also on BlackBerry Browsers, PlayStation consoles and the Tizen mobile operating system. Also, you can find AppleWebKit appearing in the Android device list for user agents.
Thus, it seems as though the AppleWebKit does not actually uniquely identify the user’s device as belonging to apple.
Which part of the user agent string does?
3 Answers 3
The main problem is that most useragent string indicate what they are compatible with instead of what they are made of. So lots of browsers that do not have AppleWebKit still report it as part of the useragent string.
I wrote a blog about this a few years ago which may interest you: https://techlab.bol.com/making-sense-user-agent-string/
If you want a list of the «rules» that determine if it is an Apple device then I can assure you that no 100% accurate list exists.
I like to think my set of rules come close; but never 100%.
Considering that many browsers allow the user to change the user-agent string to whatever they wish, I would say that no part of it identifies the device vendor.
Looking at whatismybrowser.com, it seems that your best bet is to look for the string «Mac OS X» (yes, even after name changes to «OS X» and «macOS») as that seems to be included in the user-agent string for iPad OS and iPhone OS as well, but a browser on any non-Apple device could also include it (again, the user can often change the user-agent string as they wish), so you can’t be 100% certain that they are on an Apple device just because the string is there.
Then again, someone changing their user agent to something that looks like an Apple device probably wants you to think they’re on such a device, so you might as well humor them unless you actually need to know their device in order to do something only capable on that device — in which case you probably shouldn’t do user-agent matching anyway but instead use other methods to figure out what the current device is capable of.
- Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.2 Safari/605.1.15
- Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148
- Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148
Источник
Better way to get AppleWebKit/Mobile/Safari version numbers for User-Agent string?
The iPhone app I’m working on uses WKWebView, but (my client requires that…) it must have a custom user-agent.
We’d like the user-agent string to mimic Safari’s, which looks something like this:
Mozilla/5.0 (iPhone; CPU iPhone OS 9_0_2 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13A452 Safari/601.1
I know how to set the user-agent string. The easiest is just to set the UserAgent in standard user defaults.
[[NSUserDefaults standardUserDefaults] registerDefaults:@<@"UserAgent": userAgent>];
The problem I’m having is actually with coming up with the version numbers Apple used in Safari’s User-Agent. Specifically, the AppleWebKit version, that code immediately after Mobile (13A452), and the Safari version number.
The only solution I’ve come up with involves
- instantiating a WKWebView
- loading a dummy page from a string (else step 3 fails)
- In the didFinishNavigation delegate call, evaluate a javascript to return the current user-agent
- pull the UA apart to extract those version numbers
- build a new string similar to Safari’s but with the app’s own name/version at the end and put the Safari version in parens with a «like», to result in this:
Mozilla/5.0 (iPhone; CPU iPhone OS 9_0_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13A452 (like Safari/601.1) TheAppName/1.12
(The two iPhone versions are found via provided system calls, that’s not a problem.)
Is there a better way? (Obviously, steps 3-4 could be replaced with extracting the version numbers via the javascript, but that just shifts things around.)
In short, is there any way to get those AppleWebKit/Mobile/Safari version numbers OTHER than via asking a webview instance for its own user-agent string?
I can provide some sample code or even a sample project if you can’t follow the steps above, but my intent should be clear.
Источник
Set useragent in WKWebview
How do I set a custom useragent string in a WKWebView? I’m trying to embed the version of my app so that my server-side can see what features are available. I found the following method:
But this means the useragent is only set for that single request. The first other request (e.g. a forward), will mean the useragent is reset to default again. How can I more permanently configure the wkwebview to use my custom useragent string?
6 Answers 6
You’ll be happy to hear that WKWebView just gained a customUserAgent property in iOS 9 and OSX 10.11
Update:
As of iOS 9.0 it is possible to set the user agent directly (as stated in other answers). But it is important to note that setting it will completely override the default user agent. If for some reason you need to just append a custom user agent use one of the following approaches.
or by using a sacrificial UIWebView
Old answer:
As noted in my comment you can use the same approach as described here: Change User Agent in UIWebView (iPhone SDK)
Now if you want to get the user agent you need to have an instance of a WKWebView and evaluate this javascript on it:
The problem is that if you set a custom user agent after a WKWebView has been instantiated you will always get the same user agent. To solve this problem you have to reinstantiate the web view. Here is a sample how this might look:
The code above will log:
Alternative
This could be made even simpler by using a «sacrificial» UIWebView since it evaluates javascript synchronously.
Which logs the same thing:
Right now UIWebView and WKWebView use the same user agent but this approach might cause problems if that changes in the future.
Источник
Tips & Tricks: изменяем User Agent в iPhone
Как известно, User Agent необходим для «идентификации» пользователя, а конкретнее, для определения, каким клиентом или через какое устройство заходит пользователь к вам на сайт. В зависимости от этого, можно «подставлять» необходимый контент (данные, разметку). Это актуально в последнее время по причине большого роста мобильных устройств.
В продолжении темы iPhone Dev Tips & Tricks расскажу о том, как поменять User Agent на «iPhone».
Для того, чтобы получить некий контент, который чувствительный к User Agent (в моем конкретном случае я хочу получить XML файл), необходимо выполнить следующий код:
NSURL *url = [[NSURL alloc] initWithString:@»http://domain.com/SomeXml.xml»];
NSHTTPURLResponse *response;
NSError *error;
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setValue:@»Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en)» forHTTPHeaderField:@»User-Agent»];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
Как видите, для решения задачи необходимо воспользоваться setValue:forHTTPHeaderField для вашего запроса (NSMutableURLRequest).
В моей конкретной задаче я использовал NSData, так как мне необходимо было использовать полученный XML для NSXMLParser:
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];
NSLog(@»XML is downloaded.»);
Источник
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?
14 Answers 14
Modern Swift
Here’s a suggestion for Swift 3+ projects from StackOverflow users PassKit and Kheldar:
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:
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. 😉
I had this problem too, and tried all methods. I found that only this method works (iOS 5.x): UIWebView iOS5 changing user-agent
The principle is to set the user agent permanently in the user settings. This works; Webview sends the given header. Just two lines of code:
Setting User-Agent, or User_Agent in the mutable request, or overriding the setValue in the NSHttpRequest by swizzling, — I tried all that and controlled the results with wireshark, and none of that seems to work, because Webview still uses the user agent value from the user defaults, no matter what you try to set in the NSHttpRequest.
It should work with an NSMutableURLRequest as Kuso has written.
You’ll have to use NSURLConnection to get the responseData. Set the responseData to your UIWebView and the webView should render:
Very simple in Swift. Just place the following into your App Delegate.
If you want to append to the existing agent string then:
Note: You may will need to uninstall and reinstall the App to avoid appending to the existing agent string.
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.
Источник