Getting current working directory from a Sandboxed command-line app

岁酱吖の 提交于 2021-01-27 04:12:09

问题


I'm now trying to sandbox my command-line app which is written in Objective-C.

Issue

When the app was not sandboxed, I could get the directory where the user invoked the app using [[NSFileManager defaultManager] currentDirectoryPath]. However, after sandboxing, the app always returns for current directory /Users/{MY_ACCOUNT}/Library/Containers/{BUNDLE_IDENTIFIER}/Data no matter from where the command-line app was invoked.

Example Code

Actually, I wanna know the absolute path to the files which the user passed as command arguments.

So when, for example, I invoke my command-line app like this:

$ pwd
/Users/MY_ACCOUNT/Desktop
$ ./foo/my_executable subfolder/myfile.txt

The following part:

NSURL *url = [NSURL fileURLWithFileSystemRepresentation:argv[1] isDirectory:NO relativeToURL:nil];
printf("path: %s\n", [[url absoluteURL] fileSystemRepresentation]);

returns on non-Sandboxed app correctly:

path: /Users/MY_ACCOUNT/Desktop/subfolder/myfile.txt

but on Sandboxed app:

path: /Users/MY_ACCOUNT/Library/Containers/BUNDLE_IDENTIFIER/Data/subfolder/myfile.txt

This is of course incorrect.

Question

Is there any alternative way to get the correct full paths of the passed file path arguments in a Sandboxed command-line app? Or is it just impossible and it's better I just give up to sandbox my app?


Solution

Finally, I found one of the solution by myself.

The environment property in [NSProcessInfo processInfo] has the correct current user working directory even the app is Sandboxed.

NSDictionary *env = [[NSProcessInfo processInfo] environment];
NSString *currentPath = env[@"PWD"];

At least, when I call the command in Terminal.app, it works. I'm not sure whether this PWD exists always.

Furthermore, As @daij-djan pointed out below, we don't have even the read permission for the given arguments. However, anyway the matter of this question is once resolved.

(If there is someone who know the way to read the file of which path was passed as an argument, please tell me as an answer!)


回答1:


AFAIK (I tried this a while ago, so things MIGHT have changed -- which I don't think though)

The paths passed via command line args wouldn't be accessible even if you figured out where they really are :/

===> so: thats my answer.. it is pointless Im afraid because it doesn't work




回答2:


This gets the sandboxed path for the current app.

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

Remember that "Sandbox" has to be turned on in project settings before the code above returns the sandbox path.

enter image description here



来源:https://stackoverflow.com/questions/31476313/getting-current-working-directory-from-a-sandboxed-command-line-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!