在macOS上获取当前用户的桌面路径 [英] Getting desktop path for current user on macOS

查看:742
本文介绍了在macOS上获取当前用户的桌面路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用

NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES );
NSString* theDesktopPath = [paths objectAtIndex:0];

效果很好。但是,当我使用sudo启动应用程序时,它会提供根目录的桌面路径。有没有办法总是返回当前用户的桌面(即使应用程序以sudo启动)?

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

推荐答案

我会说是没有办法做到这一点。但是我可以解释为什么我这么认为。使用NSUserDomain时,它会缩小为活动用户的文件结构。因此,就像您说的那样,当您以root用户身份访问文件时,它使用的是root目录。它不能假定另一个用户的目录,因为如果有多个用户,它将首先不知道哪个用户正在运行它,因此也不知道要访问哪个桌面目录。

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.

我找到了一种可以解决这个问题的方法。而不是使用 NSSearchPathForDirectoriesInDomains ,您必须使用环境变量自己构建路径。当您在OS X上使用 sudo 时,它不会覆盖 $ HOME 变量,因此它保留了呼叫者的主目录。您可以使用以下命令访问所有环境变量:

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];

并通过 $ HOME >

and get $HOME with

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

因此,您可以将 $ HOME 字符串,并将 / Desktop 附加到该字符串。在沙盒中这将无法正常工作,但是由于您正在谈论以root身份运行它,因此我认为您不是这样。

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.

这篇关于在macOS上获取当前用户的桌面路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆