Skip to content

Instantly share code, notes, and snippets.

@majeedyaseen
Created March 20, 2019 08:52
Show Gist options
  • Save majeedyaseen/61a177e7799ef4f68ae9174fc00f2a22 to your computer and use it in GitHub Desktop.
Save majeedyaseen/61a177e7799ef4f68ae9174fc00f2a22 to your computer and use it in GitHub Desktop.
How to create USER AGENT for iOS devices using swift
import Foundation
import UIKit
//eg. Darwin/16.3.0
func DarwinVersion() -> String {
var sysinfo = utsname()
uname(&sysinfo)
let dv = String(bytes: Data(bytes: &sysinfo.release, count: Int(_SYS_NAMELEN)), encoding: .ascii)!.trimmingCharacters(in: .controlCharacters)
return "Darwin/\(dv)"
}
//eg. CFNetwork/808.3
func CFNetworkVersion() -> String {
let dictionary = Bundle(identifier: "com.apple.CFNetwork")?.infoDictionary!
let version = dictionary?["CFBundleShortVersionString"] as! String
return "CFNetwork/\(version)"
}
//eg. iOS/10_1
func deviceVersion() -> String {
let currentDevice = UIDevice.current
return "\(currentDevice.systemName)/\(currentDevice.systemVersion)"
}
//eg. iPhone5,2
func deviceName() -> String {
var sysinfo = utsname()
uname(&sysinfo)
return String(bytes: Data(bytes: &sysinfo.machine, count: Int(_SYS_NAMELEN)), encoding: .ascii)!.trimmingCharacters(in: .controlCharacters)
}
//eg. MyApp/1
func appNameAndVersion() -> String {
guard let dictionary = Bundle.main.infoDictionary else {
return ""
}
let version = dictionary["CFBundleShortVersionString"] as! String
let name = dictionary["CFBundleName"] as! String
return "\(name)/\(version)"
}
func UAString() -> String {
return "\(appNameAndVersion()) \(deviceName()) \(deviceVersion()) \(CFNetworkVersion()) \(DarwinVersion())"
}
print("the UA String is as \(UAString().addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment