Marco Eidinger
Swifty Tech by Marco Eidinger

Follow

Swifty Tech by Marco Eidinger

Follow
Cross-platform API to determine OS version and name in Swift

Cross-platform API to determine OS version and name in Swift

Marco Eidinger's photo
Marco Eidinger
Β·Dec 5, 2022Β·

2 min read

Table of contents

  • Motivation
  • Solution: OSInfo Swift Package

In this blog post, I'll introduce a new lightweight Swift Package that helps developers easily determine the operating systems name and version in Swift for reporting purposes.

Motivation

I think it is challenging to print out the operating systems name and version on which a Swift app might run if you are in need to support various platforms.

Older APIs, like UIDevice.current.systemName , may still be useful but are not universal as UIKit cannot be used on all operating systems. Especially when we consider that Swift also runs on non-Apple platforms like Linux or Windows.

Different APIs may have been introduced, e.g. WKInterfaceDevice.current().systemName on WatchOS.

Sometimes the API behaves quirky for different environments. I am talking about Mac Catalyst. Originally this meant to make a Mac version of your iPad app. Nowadays, it is possible to run unmodified iOS apps on a Mac (Apple Silicon!).

Then UIDevice.current.systemName will return "iPadOS as a value while some might have expected or hoped for a different value ("macOS").

Similar challenges await us when determining the version despite that there is a powerful, low-level Foundation API ProcessInfo.processInfo.operatingSystemVersion that can be used across platforms.

Still, there is a discrepancy between operatingSystemVersion (a formal struct including major, minor and patch build version numbers) and operatingSystemVersionString (a localized string) when it comes to the Mac Catalyst environment.

Solution: OSInfo Swift Package

That's why I introduced OSInfo Swift Package. A universal, cross-platform API that can deal with modern platforms and environments.

import OSInfo

// Example for running as Mac Catalyst (or unmodified iOS app) on Mac
print(OS.current.name) // "macOS"
print(OS.current.version.description) // "13.0.1"
print(OS.current.displayVersion) // "Version 13.0.1 (Build 22A400)"
print(OS.appleFamily) // true
// -- alternative
print(OS(underlyingMacOS: false).name) // "iPadOS"
print(OS(underlyingMacOS: false).version.description) // "16.1"

The Swift Package is well documented, and if you still have questions, please get in touch with me.

You can find the Swift Package on GitHub.

And also on Swift Package Index.

Did you find this article valuable?

Support Marco Eidinger by becoming a sponsor. Any amount is appreciated!

See recent sponsors |Β Learn more about Hashnode Sponsors
Β 
Share this