Skip to content

Instantly share code, notes, and snippets.

@adamkaplan
Created April 30, 2019 17:58
Show Gist options
  • Save adamkaplan/a0fb391dfc6ea640f980a95a8b76abd3 to your computer and use it in GitHub Desktop.
Save adamkaplan/a0fb391dfc6ea640f980a95a8b76abd3 to your computer and use it in GitHub Desktop.
User Agent Strings in Swift
public class UserAgent {
public static let userAgent: String? = {
guard let info = Bundle.main.infoDictionary,
let appNameRaw = info["CFBundleDisplayName"] ?? info[kCFBundleIdentifierKey as String],
let appVersionRaw = info[kCFBundleVersionKey as String],
let appName = appNameRaw as? String,
let appVersion = appVersionRaw as? String
else { return nil }
#if canImport(UIKit)
let scale: String
if #available(iOS 4, *) {
scale = String(format: "%0.2f", UIScreen.main.scale)
} else {
scale = "1.0"
}
let model = UIDevice.current.model
let os = UIDevice.current.systemVersion
let ua = "\(appName)/\(appVersion) (\(model); iOS \(os); Scale/\(scale))"
#else
let ua = "\(appName)/\(appVersion)"
#endif
return ua
}()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment