Skip to content

Instantly share code, notes, and snippets.

@Mr-Alirezaa
Last active July 29, 2019 05:00
Show Gist options
  • Select an option

  • Save Mr-Alirezaa/85817d7f408d2ab20da95441e9959c3e to your computer and use it in GitHub Desktop.

Select an option

Save Mr-Alirezaa/85817d7f408d2ab20da95441e9959c3e to your computer and use it in GitHub Desktop.
This piece of code generates a User-Agent string based on the app name, os and arc. If you are using xcode you will see a placeholder instead of <#Your Class Name#>. Replace it with a name of a class in your bundle.
let userAgent: String = {
var components: [String] = []
if let appName = Bundle.main.infoDictionary?["CFBundleName"] as? String ?? Bundle.main.infoDictionary?["CFBundleIdentifier"] as? String {
let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
components.append("\(appName)/\(version)")
}
// Replace Your bundle name
let libraryBundle: Bundle? = Bundle(for: <#Your Class Name#>.self)
if let libraryName = libraryBundle?.infoDictionary?["CFBundleName"] as? String, let version = libraryBundle?.infoDictionary?["CFBundleShortVersionString"] as? String {
components.append("\(libraryName)/\(version)")
}
let system: String
#if os(OSX)
system = "macOS"
#elseif os(iOS)
system = "iOS"
#elseif os(watchOS)
system = "watchOS"
#elseif os(tvOS)
system = "tvOS"
#endif
let systemVersion = ProcessInfo().operatingSystemVersion
components.append("\(system)/\(systemVersion.majorVersion).\(systemVersion.minorVersion).\(systemVersion.patchVersion)")
let chip: String
#if arch(x86_64)
chip = "x86_64"
#elseif arch(arm)
chip = "arm"
#elseif arch(arm64)
chip = "arm64"
#elseif arch(i386)
chip = "i386"
#endif
components.append("(\(chip))")
return components.joined(separator: " ")
}()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment