如何在不知道Swift3中的用户名的情况下获取用户主目录路径(Users /"user name")

Jon*_*one 8 swift swift3

我正在编写一个func来编辑Users/johnDoe目录中的文本文件.

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)
}
Run Code Online (Sandbox Code Playgroud)

但我希望能够拥有普遍的道路.就像是

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

但对于JohnDoe文件夹.我无法找到有关如何执行此操作的任何文档.我能找到的最接近的东西是使用NSHomeDirectory().而且我不确定如何在这种情况下使用它.

当我尝试添加它...

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

我收到一个错误:

"无法将'String'类型的值转换为预期的参数类型'FileManager.SearchPathDirectory'"

我试过了.NSHomeDirectory,.NSHomeDirectory(),NShomeDirectory,NShomeDirectory()

Leo*_*bus 19

您可以使用FileManager属性homeDirectoryForCurrentUser

let homeDirURL = FileManager.default.homeDirectoryForCurrentUser
Run Code Online (Sandbox Code Playgroud)

如果您需要它可以使用早于10.12的操作系统版本,您可以使用

let homeDirURL = URL(fileURLWithPath: NSHomeDirectory())
Run Code Online (Sandbox Code Playgroud)
print(homeDirURL.path)
Run Code Online (Sandbox Code Playgroud)

  • 这将返回应用程序的主文件夹而不是用户的 if 沙箱 (5认同)

Phi*_*lls 6

应该有一种更简单的方法,但最坏的情况是,这应该有效:

let filePath = NSString(string: "~").expandingTildeInPath
Run Code Online (Sandbox Code Playgroud)