1

What is the best approach to obtaining the current user's groups in Swift for macOS?

I have come across NSUserName() for obtaining the current user's username, but based on searching and finding absolutely nothing online, I'm under the impression that such a function doesn't exist in regards to user groups.

I'm assuming I will have to leverage something outside of Swift. If that is the case, any suggestions on what I should be leveraging?

1 Answers1

0

As a last resort you could run a terminal command from swift and read the output. See this post

And to get the user group have a look at this

import Foundation

func shell(_ command: String) -> String {
    let task = Process()
    let pipe = Pipe()
    
    task.standardOutput = pipe
    task.standardError = pipe
    task.arguments = ["-c", command]
    task.launchPath = "/bin/zsh"
    task.launch()
    
    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output = String(data: data, encoding: .utf8)!
    
    return output
}

// Example usage:
shell("id")

Output of 'id':

uid=534(galuga) gid=20(staff) groups=20(staff)

mufumade
  • 400
  • 4
  • 16