Skip to content

Instantly share code, notes, and snippets.

@perlguy99
Last active December 11, 2019 20:47
Show Gist options
  • Save perlguy99/5a0035bbd96529d3b5c20a9e0cd0bdfb to your computer and use it in GitHub Desktop.
Save perlguy99/5a0035bbd96529d3b5c20a9e0cd0bdfb to your computer and use it in GitHub Desktop.
Get Documents Directory

Swift Get Documents Directory

func getDocumentsDirectory() -> URL {
    // find all possible documents directories for this user
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)

    // just send back the first one, which ought to be the only one
    return paths[0]
}

To write some text/data to the documents directory... SwiftUI

Text("Hello World")
    .onTapGesture {
        let str = "Test Message"
        let url = self.getDocumentsDirectory().appendingPathComponent("message.txt")

        do {
            try str.write(to: url, atomically: true, encoding: .utf8)
            let input = try String(contentsOf: url)
            print(input)
        } catch {
            print(error.localizedDescription)
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment