Skip to content

Instantly share code, notes, and snippets.

@gertig
Created June 6, 2012 03:42
Show Gist options
  • Save gertig/2879749 to your computer and use it in GitHub Desktop.
Save gertig/2879749 to your computer and use it in GitHub Desktop.
iOS Default User Agent
#pragma mark get user agent
+ (NSString *)defaultUserAgentString
{
@synchronized (self) {
if (!defaultUserAgent) {
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
// Attempt to find a name for this application
NSString *appName = [bundle objectForInfoDictionaryKey:@"CFBundleDisplayName"];
if (!appName) {
appName = [bundle objectForInfoDictionaryKey:@"CFBundleName"];
}
NSData *latin1Data = [appName dataUsingEncoding:NSUTF8StringEncoding];
appName = [[[NSString alloc] initWithData:latin1Data encoding:NSISOLatin1StringEncoding] autorelease];
// If we couldn't find one, we'll give up (and ASIHTTPRequest will use the standard CFNetwork user agent)
if (!appName) {
return nil;
}
NSString *appVersion = nil;
NSString *marketingVersionNumber = [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
NSString *developmentVersionNumber = [bundle objectForInfoDictionaryKey:@"CFBundleVersion"];
if (marketingVersionNumber && developmentVersionNumber) {
if ([marketingVersionNumber isEqualToString:developmentVersionNumber]) {
appVersion = marketingVersionNumber;
} else {
appVersion = [NSString stringWithFormat:@"%@ rv:%@",marketingVersionNumber,developmentVersionNumber];
}
} else {
appVersion = (marketingVersionNumber ? marketingVersionNumber : developmentVersionNumber);
}
NSString *deviceName;
NSString *OSName;
NSString *OSVersion;
NSString *locale = [[NSLocale currentLocale] localeIdentifier];
#if TARGET_OS_IPHONE
UIDevice *device = [UIDevice currentDevice];
deviceName = [device model];
OSName = [device systemName];
OSVersion = [device systemVersion];
#else
deviceName = @"Macintosh";
OSName = @"Mac OS X";
// From http://www.cocoadev.com/index.pl?DeterminingOSVersion
// We won't bother to check for systems prior to 10.4, since ASIHTTPRequest only works on 10.5+
OSErr err;
SInt32 versionMajor, versionMinor, versionBugFix;
err = Gestalt(gestaltSystemVersionMajor, &versionMajor);
if (err != noErr) return nil;
err = Gestalt(gestaltSystemVersionMinor, &versionMinor);
if (err != noErr) return nil;
err = Gestalt(gestaltSystemVersionBugFix, &versionBugFix);
if (err != noErr) return nil;
OSVersion = [NSString stringWithFormat:@"%u.%u.%u", versionMajor, versionMinor, versionBugFix];
#endif
// Takes the form "My Application 1.0 (Macintosh; Mac OS X 10.5.7; en_GB)"
[self setDefaultUserAgentString:[NSString stringWithFormat:@"%@ %@ (%@; %@ %@; %@)", appName, appVersion, deviceName, OSName, OSVersion, locale]];
}
return [[defaultUserAgent retain] autorelease];
}
return nil;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment