Is there any other API I can use to get user name from any valid user id?
You can use
getpwuidfor that. If you always get
rootback, that’s probably because you’re always passing it 0 as the UID. If you pass it a different UID, you’ll get a different name.
let p = getpwuid(501)! print(String(cString: p.pointee.pw_name)) // prints "quinn" on my machine
How can I get the currently active logged-in user in a background daemon considering fast user switching?
I’m going to caution against doing this. In my experience, most folks who ask this question are suffering from architectural problems. For example, in your case, you’re asking about the “currently active logged-in user”, but macOS can have multiple currently active GUI login sessions, including at most one on the console and zero or more logged in via screen sharing.
I discuss this issue in detail in QA1133 Determining console user login status and the documents it links to.
Share and Enjoy
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"