How To Add Text To File

I posted about creating and reading text files here. Now it’s time to add text to file.

When you write again to the existing file then it’ll be overwritten.

First, you need a file URL and some String content.

let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentDirectory.appendingPathComponent(“some_file.txt”)
let content = “Content to add…”

Then create FileHandle instance, it’ll return nil when the file doesn’t exist. Then move the pointer to the end of the file, add your content, and close the file.

if let handle = try? FileHandle(forWritingTo: fileURL) {
    handle.
seekToEndOfFile() // moving pointer to the end
    handle.
write(content.data(using: .utf8)!) // adding content
    handle.
closeFile() // closing the file
}