Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@bryanburgers
Created October 9, 2015 11:44
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bryanburgers/daa09d5d8c3b61c6d98a to your computer and use it in GitHub Desktop.
Save bryanburgers/daa09d5d8c3b61c6d98a to your computer and use it in GitHub Desktop.
//
// UserAgent.swift
//
import Foundation
class UserAgent {
static func getUserAgent() -> String {
let bundleDict = NSBundle.mainBundle().infoDictionary!
let appName = bundleDict["CFBundleName"] as! String
let appVersion = bundleDict["CFBundleShortVersionString"] as! String
let appDescriptor = appName + "/" + appVersion
let currentDevice = UIDevice.currentDevice()
let osDescriptor = "iOS/" + currentDevice.systemVersion
let hardwareString = self.getHardwareString()
return appDescriptor + " " + osDescriptor + " (" + hardwareString + ")"
}
static func getHardwareString() -> String {
var name: [Int32] = [CTL_HW, HW_MACHINE]
var size: Int = 2
sysctl(&name, 2, nil, &size, &name, 0)
var hw_machine = [CChar](count: Int(size), repeatedValue: 0)
sysctl(&name, 2, &hw_machine, &size, &name, 0)
let hardware: String = String.fromCString(hw_machine)!
return hardware
}
}
@GPretadoR
Copy link

GPretadoR commented Dec 19, 2019

Works for Swift 5:

class UserAgent {
    static func getUserAgent() -> String {
        let bundleDict = Bundle.main.infoDictionary!
        let appName = bundleDict["CFBundleName"] as! String
        let appVersion = bundleDict["CFBundleShortVersionString"] as! String
        let appDescriptor = appName + "/" + appVersion

        let currentDevice = UIDevice.current
        let osDescriptor = "iOS/" + currentDevice.systemVersion

        let hardwareString = self.getHardwareString()

        return appDescriptor + " " + osDescriptor + " (" + hardwareString + ")"
    }

    static func getHardwareString() -> String {
        var name: [Int32] = [CTL_HW, HW_MACHINE]
        var localname: [Int32] = [CTL_HW, HW_MACHINE]
        var size: Int = 2
        localname = name
        sysctl(&name, 2, nil, &size, &localname, 0)
        var hw_machine = [CChar](repeating: 0, count: Int(size)) //[CChar](count: Int(size), repeatedValue: 0)
        sysctl(&name, 2, &hw_machine, &size, &localname, 0)

        let hardware: String = String(cString: hw_machine)
        return hardware
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment