如何在不知道Swift3中的用户名的情况下获取用户主目录路径(Users
发布时间:2020-12-14 02:28:07 所属栏目:百科 来源:网络整理
导读:我正在编写一个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)
我正在编写一个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) } 但我希望能够拥有普遍的道路.就像是 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 我收到一个错误:
我试过了.NSHomeDirectory,.NSHomeDirectory(),NShomeDirectory,NShomeDirectory()
您可以使用FileManager属性
homeDirectoryForCurrentUser
let homeDirURL = FileManager.default.homeDirectoryForCurrentUser 如果您需要它可以使用早于10.12的操作系统版本,您可以使用 let homeDirURL = URL(fileURLWithPath: NSHomeDirectory()) print(homeDirURL.path) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |