Programmatically get iOS, iPadOS, macOS Catalyst Operating System Name and Version and a model identifier of iPhone, iPad, Mac devices.

Programmatically get iOS, iPadOS, macOS Catalyst Operating System Name and Version and a model identifier of iPhone, iPad, Mac devices.

Here is a simple way to programmatically get the operating system name and version of your iOS, iPadOS and macOS.

The below code will also return the value of iPhone, iPad and Mac Model identifier to help you know if it’s MacBook or iMac in Mac’s case or iPhone 11 Pro or iPhone 13 Pro etc.

Step 01: First import IOKit, It is only required for macOS Catalyst app-specific code.

#if targetEnvironment(macCatalyst)
import IOKit
#endif

Step 02: Now paste the below function in your UIViewController class file. It will work perfectly for each use case the app runs on iPhone, iPad or Mac.

func systemVersion() -> String {
        #if targetEnvironment(macCatalyst)
        // Reference: https://stackoverflow.com/questions/20070333/obtain-model-identifier-string-on-os-x
        let service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice"))
        var modelIdentifier: String?
        if let modelData = IORegistryEntryCreateCFProperty(service, "model" as CFString, kCFAllocatorDefault, 0).takeRetainedValue() as? Data {
            modelIdentifier = String(data: modelData, encoding: .utf8)?.trimmingCharacters(in: .controlCharacters)
        }
        IOObjectRelease(service)
        return "\(modelIdentifier ?? "")" + " " + "macOS" + " " + "\(ProcessInfo.processInfo.operatingSystemVersionString)"
        #endif
        #if !targetEnvironment(macCatalyst)
        // Reference: https://stackoverflow.com/questions/26028918/how-to-determine-the-current-iphone-device-model
        var utsnameInstance = utsname()
        uname(&utsnameInstance)
        let machineString: String? = withUnsafePointer(to: &utsnameInstance.machine) {
            $0.withMemoryRebound(to: CChar.self, capacity: 1) {
                ptr in String.init(validatingUTF8: ptr)
            }
        }
        return "\(machineString ?? "")" + " " + "\(UIDevice.current.systemName)" + " " + "\(UIDevice.current.systemVersion)"
        #endif
}

Step 03: Now call the function like this in your ViewDidLoad.

print("\(self.systemVersion())")

And It will return value something like this:

For iPhone: iPhone12,3 iOS 15.2
For iPad: iPad6,3 iPadOS 15.2
For Mac: iMac18,3 macOS Version 12.1 (Build 21C52)

I hope this helps you,

Thanks & Regards
Mandar Apte

Leave a Reply

Your email address will not be published.