JonnyTombstone
JonnyTombstone

Reputation: 249

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

I am making a func that edits a text file in the Users/johnDoe Dir.

let filename = "random.txt"
let filePath = "/Users/johnDoe"
let replacementText = "random bits of text"
do {

 try replacementText.write(toFile: filePath, atomically: true, encoding: .utf8)

}catch let error as NSError {
print(error: + error.localizedDescription)
}

But I want to be able to have the path universal. Something like

let fileManager = FileManager.default
    let downloadsURL =  FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first! as NSURL
    let downloadsPath = downloadsURL.path

but for the JohnDoe folder. I haven't been able to find any documentation on how to do this. The closest thing I could find mentioned using NSHomeDirectory(). And I am not sure how to use it in this context.

when I try adding it like...

let fileManager = FileManager.default
    let downloadsURL =  FileManager.default.urls(for: NSHomeDirectory, in: .userDomainMask).first! as NSURL
    let downloadsPath = downloadsURL.path

I get an error:

"Cannot Convert value of type 'String' to expected argument type 'FileManager.SearchPathDirectory'"

I've tried it .NSHomeDirectory, .NSHomeDirectory(), NShomeDirectory, NShomeDirectory()

Upvotes: 23

Views: 16854

Answers (4)

Andrew_STOP_RU_WAR_IN_UA
Andrew_STOP_RU_WAR_IN_UA

Reputation: 11416

Works even in Sandboxed apps :

(works even in old swift language versions and old macOS versions)

public extension URL {
    static var userHome : URL   {
        URL(fileURLWithPath: userHomePath, isDirectory: true)
    }
    
    static var userHomePath : String   {
        let pw = getpwuid(getuid())

        if let home = pw?.pointee.pw_dir {
            return FileManager.default.string(withFileSystemRepresentation: home, length: Int(strlen(home)))
        }
        
        fatalError()
    }
}

Testing solution on sandboxed App:

enter image description here

Upvotes: 6

Leo Dabus
Leo Dabus

Reputation: 236260

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)

Upvotes: 41

Justin Vallely
Justin Vallely

Reputation: 6089

Swift 5 (and maybe lower)

let directoryString: String = NSHomeDirectory()
let directoryURL: URL = FileManager.default.homeDirectoryForCurrentUser

Upvotes: 0

Phillip Mills
Phillip Mills

Reputation: 31016

There should be an easier way but -- at worst -- this should work:

let filePath = NSString(string: "~").expandingTildeInPath

Upvotes: 5

Related Questions