Clicky

iOS Dev Nugget 262 Apple Device Names API

.

Need to run a code review on your codebase? Hire me

This is a continuation of #260 where I talk about including the app version and device Name in feedback/support emails. After thinking about it, I created Apple Device Names. It provides a simple API that maps iPhone10,6iPhone X.

It's just a curl command away:

$ curl http://appledevicenames.com/device/iPhone10,6

iPhone X

So to generate something like this:

For info/diagnostic purposes:
  App v1.0.0 build 23 on iPhone X, iOS 11.0.3

You can do this in Swift:

//Stick this somewhere
private func deviceModel() -> String? {
    var keys = [CTL_HW, HW_MACHINE]
    var requiredSize = 0
    let fetchSizeResult = sysctl(&keys, UInt32(keys.count), nil, &requiredSize, nil, 0)
    guard fetchSizeResult == 0 else { return nil }
    var data = [CChar](repeating: 0, count: requiredSize)
    let fetchResult = sysctl(&keys, UInt32(keys.count), &data, &requiredSize, nil, 0)
    guard fetchResult == 0 else { return nil }
    return String(validatingUTF8: data)
}

//Stick this somewhere
func withDeviceName(block: @escaping (String) -> Void)  {
    let fallbackName = "Unknown"
    if let model = deviceModel(),
    let url = URL(string: "https://appledevicenames.com/device/\(model)") {
        URLSession.shared.dataTask(with: url) { data, _ , _ in
            DispatchQueue.main.async {
                if let data = data, let name = String(data: data, encoding: .utf8) {
                    block(name)
                } else {
                    block(fallbackName)
                }
            }
        }.resume()
    } else {
        block(fallbackName)
    }
}

//Calling code
withDeviceName { deviceName in
    let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString")
    let buildNumber = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion")
    let osVersion = UIDevice.current.systemVersion
    if let appVersion=appVersion, let buildNumber=buildNumber {
        let body = "For info/diagnostic purposes:\n  App v\(appVersion) build \(buildNumber) on \(deviceName), iOS \(osVersion)"
        //body = "For info/diagnostic purposes:\n  App v1.0.0 build 23 on iPhone X, iOS 11.0.3"
        //Use body
    }
}

Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues