Getting desktop path for current user on macOS

2020-07-10 01:15发布

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)?

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-07-10 01:53

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 use sudo 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 with

[[NSProcessInfo processInfo] environment];

and get $HOME with

[[[NSProcessInfo processInfo] environment] objectForKey:@"HOME"];

So 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.

查看更多
欢心
3楼-- · 2020-07-10 01:56

I use the statement below.

[NSURL fileURLWithPath:[NSHomeDirectory()stringByAppendingPathComponent:@"Desktop"]]
查看更多
登录 后发表回答