How to get user home directory path (Users/“user name”) without knowing the username in Swift3

前端 未结 3 1049
北荒
北荒 2020-12-19 01:00

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 = \"         


        
相关标签:
3条回答
  • 2020-12-19 01:17

    You can use FileManager property homeDirectoryForCurrentUser

    let homeDirURL = FileManager.default.homeDirectoryForCurrentUser
    

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

    let homeDirURL = URL(fileURLWithPath: NSHomeDirectory())
    

    print(homeDirURL.path)
    
    0 讨论(0)
  • 2020-12-19 01:40

    There should be an easier way but -- at worst -- this should work:

    let filePath = NSString(string: "~").expandingTildeInPath
    
    0 讨论(0)
  • 2020-12-19 01:41

    Maybe

    FileManager.homeDirectoryForCurrentUser: URL
    

    It's listed as "beta" for 10.12, though.

    0 讨论(0)
提交回复
热议问题