To create a file in Swift, you can use the FileManager
class which provides methods for creating, deleting, moving and copying files and directories.
The following code snippet creates a new file named "example.txt" in the documents directory of your app:
main.swift349 chars10 lines
This creates fileURL
by appending the fileName
to the URL for the documents directory, then writes the string "Hello, World!" to the file using the .write(to:atomically:encoding:)
method.
If the file already exists, this code will overwrite its contents. If you'd like to add to an existing file, you can use the FileHandle
class to append data to the end of a file.
gistlibby LogSnag