Created
March 2, 2021 18:59
-
-
Save leoniralves/8578516153a40c08d111ba29a7fc126b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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