loading...

Programmatically determine OS is up to date or outdated on windows or mac osx .

jsgurugit profile image jsguru ・2 min read

Recently I have developed Software for Windows and Mac osx.
Here I needed to determine my os is up to date or outdated programmatically.

For windows version, programming language is C# and for mac osx version, swift is used.

I could implement the function in C# because there are C# code snippet related my purpose over internet.

But unfortunately, no luck for Mac osx and swift.
There are too much articles to get Mac osx or iOS version.
They was not my concerns.

Below is C# implementation for windows version.

bool CheckIsOSUpdated()
{
    IUpdateSession updateSession = new UpdateSession();
    IUpdateSearcher searcher;
    searcher = updateSession.CreateUpdateSearcher();
    ISearchResult updates = searcher.Search("IsInstalled=0 and Type='Software' and IsHidden=0");
    //ISearchResult updates = searcher.Search("IsInstalled=0");
    if (updates.Updates.Count == 0)
        return true;
    else
        return false;
}

Then the implementation in swift for Mac osx version is

import SwiftShell

func getIsOSXUpdate() -> Bool {
    // softwareupdate --list|tee
    // let command = runAsync("softwareupdate", "--list").stdout.runAsync("tee")
    let command = runAsync("softwareupdate", "--list")
    do {
        try command.finish()
    } catch {
        NSLog("could not collect available updates.")
        return false
    }

    _ = command.stdout.read()
    let error = command.stderror.read()

    if error.contains("No new software available") {
        return true
    }

    return false
}

You may wonder why stderror is used rather than stdout.
When you run softwareupdate --list on terminal, you will see the result like below if your Mac os is up to date.

JSGURUs-Mac:~ jsguru$ softwareupdate --list
Software Update Tool

Finding available software
No new software available.
JSGURUs-Mac:~ jsguru$ 

Strangely, stdout returns "Software Update Tool\n\nFinding available software\n" and stderror returns "No new software available.\n".
That's why stderror is used.

I hope these code snippets help you.

Discussion

pic
Editor guide
Collapse
buinauskas profile image
Evaldas
return updates.Updates.Count == 0;

Shorter 🙂

Collapse
jsgurugit profile image
jsguru Author

Yes, you are right.