How do I get the users home directory in a sandboxed app?

前端 未结 3 1809
[愿得一人]
[愿得一人] 2020-12-09 02:49

NSHomeDirectory() is retuning my sandbox root, not my home directory. [@\"~\" stringByExpandingTildeInPath] is doing the same thing.

This <

3条回答
  •  暖寄归人
    2020-12-09 03:40

    If you want the path to the user's real home directory you can use:

    char *realHome = getpwuid(getuid())->pw_dir;
    

    Full example:

    #include 
    #include 
    #include 
    #include 
    
    NSString *RealHomeDirectory() {
        struct passwd *pw = getpwuid(getuid());
        assert(pw);
        return [NSString stringWithUTF8String:pw->pw_dir];
    }
    

    This gives you the path to the user's home, but does not automatically give you access to that folder. As noted in comments, you can use this path for:

    • providing a sane default folder for the open/save dialogs
    • detecting whether you are in a sandbox, by comparing the result to NSHomeDirectory()

提交回复
热议问题