Using file systems is a perfect place to store images, audios, or any other type of file.
Comparing to other languages it’s fairly simple.
First, you need to get a URL instance of a path where you want to save or write. In example, there is Document Directory but you can use different if you need them, there are a lot of them.
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
Then append your file name with the extension or add the extension in a separate method.
let fileURL = documentDirectory.appendingPathComponent(“some_file.txt”)
or
var fileURL = documentDirectory.appendingPathComponent(“some_file”)
fileURL.appendPathExtension(“txt”)
To save text file you need some String.
let writeContent = “Your content…”
And save it to fileURL created previously.
do {
try writeContent.write(to: fileURL, atomically: true, encoding: .utf8)
print(“Content writted successfully!”)
} catch {
print(error)
}
The second parameter indicated whether the file can be saved partially. If it’s set to true you’re sure that it’ll save completely or not at all.
To read from file
do {
let readContent = try String(contentsOf: fileURL, encoding: .utf8)
print(“Read content: \(readContent)“)
} catch {
print(error)
}
Remember that it’s synchronous so don’t do it on main thread because it can freeze your application.