Skip to content

Instantly share code, notes, and snippets.

@drewster99
Created May 20, 2021 17:00
Show Gist options
  • Save drewster99/c09112daac441a6b4c3395247f2e15f9 to your computer and use it in GitHub Desktop.
Save drewster99/c09112daac441a6b4c3395247f2e15f9 to your computer and use it in GitHub Desktop.
Swift - Generates a suitable UserAgent string on iOS / macOS / tvOS
static let userAgent: String = {
let info = Bundle.main.infoDictionary
let executable = (info?[kCFBundleExecutableKey as String] as? String) ??
(ProcessInfo.processInfo.arguments.first?.split(separator: "/").last.map(String.init)) ??
"Unknown"
let bundle = info?[kCFBundleIdentifierKey as String] as? String ?? "Unknown"
let appVersion = info?["CFBundleShortVersionString"] as? String ?? "Unknown"
let appBuild = info?[kCFBundleVersionKey as String] as? String ?? "Unknown"
let osNameVersion: String = {
let version = ProcessInfo.processInfo.operatingSystemVersion
let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
let osName: String = {
#if os(iOS)
#if targetEnvironment(macCatalyst)
return "macOS(Catalyst)"
#else
return "iOS"
#endif
#elseif os(watchOS)
return "watchOS"
#elseif os(tvOS)
return "tvOS"
#elseif os(macOS)
return "macOS"
#elseif os(Linux)
return "Linux"
#elseif os(Windows)
return "Windows"
#else
return "Unknown"
#endif
}()
return "\(osName) \(versionString)"
}()
return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion))"
}()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment