Home > OS >  Swift MacOS know the version of the OS and Xcode
Swift MacOS know the version of the OS and Xcode

Time:03-27

I should print for a program on macOS, the Xcode and OS version.

Eg:

OS: macOS 12.3
Xcode: 13.3

How can I do?

Edit:

Maybe for the mac version I did it:

let osVersion = ProcessInfo.processInfo.operatingSystemVersion
let pasteboard = NSPasteboard.general
pasteboard.clearContents()
pasteboard.setString("MacOS: 
\(osVersion.majorVersion).
\(osVersion.minorVersion).
\(osVersion.patchVersion)", forType: .string)

CodePudding user response:

For the macOS version, you can indeed get it from ProcessInfo.processInfo.operatingSystemVersion.

For the Xcode version, you can first find where Xcode's bundle is from its bundle ID, find its bundle, and get the version from its bundle's Info.plist as a string.

guard let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.apple.dt.Xcode"),
      let bundle = Bundle(url: url) else {
    print("Xcode is not installed")
    exit(1)
}

guard let infoDict = bundle.infoDictionary,
      let version = infoDict["CFBundleShortVersionString"] as? String else {
    print("No version found in Info.plist")
    exit(1)
}
print(version) // Example output: 13.1

You can replace the let url = ... step with a NSOpenPanel prompt to let the user choose where their Xcode is installed too.

  • Related