Skip to content

Instantly share code, notes, and snippets.

@leoniralves
Created March 2, 2021 18:59
Show Gist options
  • Save leoniralves/8578516153a40c08d111ba29a7fc126b to your computer and use it in GitHub Desktop.
Save leoniralves/8578516153a40c08d111ba29a7fc126b to your computer and use it in GitHub Desktop.
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
func writeOnFile(str: String) {
let filename = getDocumentsDirectory().appendingPathComponent("output.txt")
do {
if FileManager.default.fileExists(atPath: filename.path), let data = "\(str)\n".data(using: .utf8) {
do {
let fileHandle = try FileHandle(forWritingTo: filename)
fileHandle.seekToEndOfFile()
fileHandle.write(data)
fileHandle.closeFile()
} catch {
print(error)
}
} else {
try str.write(to: filename, atomically: false, encoding: String.Encoding.utf8)
}
} catch {
// failed to write file – bad permissions, bad filename, missing permissions, or more likely it can't be converted to the encoding
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment