I use
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES );
NSString* theDesktopPath = [paths objectAtIndex:0];
It works well. But when I launch the application with sudo it gives the root's desktop path. Is there any way to return current user's desktop always (even if the app is started with sudo)?
I would say there is no way to do this. But I can explain why I think that. When you use NSUserDomain it narrows down to the active user's file structure. So like you said when you're accessing files as the root user it uses root's directories instead. It couldn't assume the directories of another user because if there were multiple users it would not know which was running it in the first place and therefore not know which desktop directory to access.
I found a way around this that should work for you. Instead of using the
NSSearchPathForDirectoriesInDomains
you will have to build your path yourself using environment variables. When you usesudo
on OS X it doesn't overwrite the$HOME
variable so it maintains the caller's home directory. You can access all the environment variables withand get
$HOME
withSo you can grab
$HOME
as a string and append/Desktop
to it. This would not work correctly in a sandbox but since you're talking about running it as root I assume you're not.I use the statement below.