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

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

问题描述

我正在制作一个功能,用于编辑Users/johnDoe Dir中的文本文件.

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属性

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天全站免登陆