I am implementing a small logger, in which I am writing to a TXT file. I wanted the last event to be at the top of the file but I'm having trouble getting this to work. All examples on the internet are using "fileHandle.seekToEndOfFile()" to write at the end of the file.
This is what I have:
private static func writeToFile(text: String) {
guard let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first else { return }
guard let writePath = NSURL(fileURLWithPath: path).appendingPathComponent(Logger.folderName) else { return }
let fileManager = FileManager.default
try? fileManager.createDirectory(atPath: writePath.path, withIntermediateDirectories: true)
let file = writePath.appendingPathComponent(Logger.fileName)
if !fileManager.fileExists(atPath: file.path) {
do {
try "".write(toFile: file.path, atomically: true, encoding: String.Encoding.utf8)
} catch _ {
}
}
let msgWithLine = text + "\n"
do {
let fileHandle = try FileHandle(forWritingTo: file)
//fileHandle.seekToEndOfFile()
fileHandle.write(msgWithLine.data(using: .utf8)!)
fileHandle.closeFile()
} catch {
print("Error writing to file \(error)")
}
}
With this code, I write in the first line but nevertheless, I am always rewriting what is on the first line.
How can I change this to whatever is in the first be taken to a line below and then write new content in the first line?
Thank you!!