How to get the user agent on iOS?
You don’t actually need to make the request in order to get the user-agent. Just return NO from the following delegate method and retain the user-Agent header:
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
It might look something like this:
-(BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType
{
userAgent = [[request valueForHTTPHeaderField:@"User-Agent"] copy];
NSLog(@"user-agent: %@", userAgent);
_webView.delegate = nil;
[_webView release];
return NO;
}
Mobile application in every request must send his User-Agent
header with build version and device information
User agent configuration info
So, user agent should be like:
User-Agent: <AppName>/version (<system-information>) <platform> (<platform-details>) <extensions>
For iOS:
User-Agent: <AppName/<version> (<iDevice platform>; <Apple model identifier>; iOS/<OS version>) CFNetwork/<version> Darwin/<version>
How to get each of the components?
Headers Key - u can hardcode or use some constant values
AppName and version - grab from
Info.plist
let infoPlist = try? PListFile<InfoPlist>() let appName = infoPlist.data.bundleName let version = infoPlist.data.versionNumber let build = infoPlist.data.buildNumber
Info about Device
modelName
- you can obtain like described here
let modelName = UIDevice.current.modelName
other components:
let platform = UIDevice.current.systemName
let operationSystemVersion = ProcessInfo.processInfo.operatingSystemVersionString
CFNetwork version
static var cfNetworkVersion: String? { guard let bundle = Bundle(identifier: "com.apple.CFNetwork"), let versionAny = bundle.infoDictionary?[kCFBundleVersionKey as String], let version = versionAny as? String else { return nil } return version }
from here
Darwin Version
var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.release) let darvinVersionString = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) }
from here
Result:
MyApp/1.8.199 (iOS; iPhone XS; Version 13.3 (Build 17C45)) CFNetwork/1121.2.1 Darvin/19.3.0
A simpler way to ascertain the user agent in iOS is to get it directly from a UIWebView
using the accepted answer to this SO post. To quote that answer:
The solution was to create a UIWebView and then just use javascript to pull out the user agent.
UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectZero]; NSString* secretAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];