How to Get User Home Directory Path (Users/"User Name") Without Knowing the Username in Swift3

How to get user home directory path (Users/ user name ) without knowing the username in Swift3

You can use FileManager property homeDirectoryForCurrentUser

let homeDirURL = FileManager.default.homeDirectoryForCurrentUser

If you need it to work with earlier OS versions than 10.12 you can use

let homeDirURL = URL(fileURLWithPath: NSHomeDirectory())

print(homeDirURL.path)

How to get user path with NSURL

To get the home directory in Swift you just need to use the following:

let homeDirectory = NSHomeDirectory()

This will print out:

/Users/FOLDER_NAMED_AFTER_USER

Swift 3 : How to get path of file saved in Documents folder

First, separate name and extension:

Bundle.main.path(forResource: "Owl", ofType: "jpg")

Second, separate (mentally) your bundle and the Documents folder. They are two completely different things. If this file is the Documents folder, it absolutely is not in your main bundle! You probably want something like this:

let fm = FileManager.default
let docsurl = try! fm.url(for:.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let myurl = docsurl.appendingPathComponent("Owl.jpg")

Third, if Owl is an image asset in the asset catalog, then say

let im = UIImage(named:"Owl") // or whatever its name is

How do I check if the current user is an admin for a Realm SyncUser?

Perfect timing! We JUST added that feature 4 days ago. :)

Version 2.5.0 was shipped a week ago, so it won't be in any of the current release bundles until the next version ships. In the meantime, you can just pull the master branch of the Realm Cocoa repo (through CocoaPods or manually) and build it yourself to get that functionality right now.

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

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

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

Full example:

#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include <assert.h>

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


Related Topics



Leave a reply



Submit