save data to file swift code example
Example 1: swift save data to file
let file = "file.txt"
let text = "some text"
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let fileURL = dir.appendingPathComponent(file)
do {
try text.write(to: fileURL, atomically: false, encoding: .utf8)
}
catch {}
do {
let text2 = try String(contentsOf: fileURL, encoding: .utf8)
}
catch {}
}
Example 2: save file with % swift
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}