Get current user's home directory
Asked Answered
G

3

22

I'm developing a Cocoa Objective-C application that will run on Mac OS X. I need to get the full path of the current user's home directory:

/Users/MyUser/

Is there a standard function that does that in Objective-C/Cocoa?

Grunt answered 5/8, 2011 at 15:4 Comment(0)
B
48

NSHomeDirectory: “Returns the path to the current user’s home directory.”

Example:

NSLog(@"Current user’s home directory is %@", NSHomeDirectory());
Borrowing answered 5/8, 2011 at 15:5 Comment(1)
Swift: print("Current user’s home directory is \(NSHomeDirectory())")Frederickson
C
5

Since macOS 10.12 you can also use FileManager.default.homeDirectoryForCurrentUser, see the documentation.

Cathrine answered 2/7, 2018 at 21:47 Comment(0)
E
3

You can use FileManager.default.homeDirectoryForCurrentUser -> URL or NSHomeDirectory() -> String - they both return the same thing, just in different types.

There's an important caveat, though:

In macOS, it is the application’s sandbox directory or the current user’s home directory (if the application is not in a sandbox).

If you're building your app to be distributed in the App Store, you're going to have to deal with the fact that these functions return the sandboxed home and not the directory the user thinks of as ~.

Enfeoff answered 19/1, 2021 at 23:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.