如何在不知道 Swift3 中的用户名的情况下获取用户主目录路径(用户/“用户名") [英] How to get user home directory path (Users/"user name") without knowing the username in Swift3

查看:27
本文介绍了如何在不知道 Swift3 中的用户名的情况下获取用户主目录路径(用户/“用户名")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个功能来编辑用户/johnDoe 目录中的文本文件.

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

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

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

我收到一个错误:

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

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

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

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

推荐答案

您可以使用 FileManager 属性 homeDirectoryForCurrentUser

You can use FileManager property homeDirectoryForCurrentUser

let homeDirURL = FileManager.default.homeDirectoryForCurrentUser

如果您需要它与 10.12 之前的操作系统版本一起使用,您可以使用

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

let homeDirURL = URL(fileURLWithPath: NSHomeDirectory())

<小时>

print(homeDirURL.path)

这篇关于如何在不知道 Swift3 中的用户名的情况下获取用户主目录路径(用户/“用户名")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆