write txt documents directory in swift

To write a text document to a directory in Swift, you can use the FileManager class to access and modify the file system.

Here's an example of how to write a string to a text file and safely handle errors:

main.swift
func writeTextToFile(_ text: String, fileName: String, directory: FileManager.SearchPathDirectory, subdirectory: String? = nil) throws {

    // Get the documents directory for the user's home directory
    let fileManager = FileManager.default
    var directoryURL = try fileManager.url(for: directory, in: .userDomainMask, appropriateFor: nil, create: true)

    // Append an optional subdirectory to the documents directory
    if let subdirectory = subdirectory {
        directoryURL.appendPathComponent(subdirectory, isDirectory: true)
        try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
    }

    // Append the filename to the directory URL
    let fileURL = directoryURL.appendingPathComponent(fileName)

    // Write the text to the file atomically (safe way to write files)
    try text.write(to: fileURL, atomically: true, encoding: .utf8)
}
912 chars
19 lines

You can call this function passing in the text you want to write, the name of the file, and the directory where you want to create the file.

Here's an example of how to use this function to write "Hello, world!" to a text file named "example.txt" in the documents directory:

main.swift
do {
    try writeTextToFile("Hello, world!", fileName: "example.txt", directory: .documentDirectory)
}
catch {
    print("Error writing file: \(error)")
}
156 chars
7 lines

This code will create a text file named "example.txt" within the documents directory of your app, with the string "Hello, world!" written to it in UTF-8 encoding.

gistlibby LogSnag