如何在不知道Swift 3中的用户名的情况下获取用户主目录路径(Users/“用户名”)

knpiaxh1  于 2023-04-10  发布在  Swift
关注(0)|答案(5)|浏览(136)

我正在创建一个函数,用于编辑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)
}

但是我希望能够有一条普遍的道路。就像

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

但是对于JohnDoe文件夹。我还没有找到任何关于如何做到这一点的文档。我能找到的最接近的东西提到使用NSHomeDirectory()。我不知道如何在这种情况下使用它。
当我试着把它加到

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

我得到一个错误:
“无法将类型”String“的值转换为预期的参数类型”FileManager. SearchPathDirectory“
我试过了.NSHomeDirectory,.NSHomeDirectory(),NShomeDirectory,NShomeDirectory()

qv7cva1a

qv7cva1a1#

您可以使用FileManager属性homeDirectoryForCurrentUser

let homeDirURL = FileManager.default.homeDirectoryForCurrentUser

如果您需要它与比10.12更早的OS版本一起工作,您可以使用

let homeDirURL = URL(fileURLWithPath: NSHomeDirectory())
print(homeDirURL.path)
6yt4nkrj

6yt4nkrj2#

应该有一个更简单的方法,但在最坏的情况下,这应该是可行的:

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

1zmg4dgp3#

Swift 5(可能更低)

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

1tuwyuhd4#

以下解决方案在沙盒应用中也能正常工作:

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

沙盒应用程序上的测试解决方案:

ncecgwcz

ncecgwcz5#

也许吧

FileManager.homeDirectoryForCurrentUser: URL

不过,它被列为10.12的“测试版”。

相关问题