How to get user home directory path (Users/“user n

2019-02-17 12:03发布

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

标签: swift swift3
3条回答
霸刀☆藐视天下
2楼-- · 2019-02-17 12:33

Maybe

FileManager.homeDirectoryForCurrentUser: URL

It's listed as "beta" for 10.12, though.

查看更多
趁早两清
3楼-- · 2019-02-17 12:47

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

let filePath = NSString(string: "~").expandingTildeInPath
查看更多
相关推荐>>
4楼-- · 2019-02-17 12:59

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)
查看更多
登录 后发表回答