I want to write sensor data to a file as the sensor updates within the method. I need to append the data as it updates, but my file overwrites with the last sensor output when I
Use seekToEndOfFile
let myHandle = FileHandle.init(forWritingAtPath: fileUrl.path)
myHandle.seekToEndOfFile
myHandle.write(strTowrite.data(using: String.Encoding.utf8)!)
myHandle.closeFile()
Just Try using This
//MARK:- Extension for String
extension String
{
func appendLineToURL(fileURL: URL) throws
{
try (self + "\n").appendToURL(fileURL: fileURL)
}
func appendToURL(fileURL: URL) throws
{
let data = self.data(using: String.Encoding.utf8)!
try data.append(fileURL: fileURL)
}
}
//MARK:- Extension for File data
extension Data
{
func append(fileURL: URL) throws {
if let fileHandle = FileHandle(forWritingAtPath: fileURL.path)
{
defer
{
fileHandle.closeFile()
}
fileHandle.seekToEndOfFile()
fileHandle.write(self)
}
else
{
try write(to: fileURL, options: .atomic)
}
}
}
Usage:
try newLine.appendToURL(fileURL: path!)
These Extension will Append Your NewLine Which you exactly looking for to Do,
This will just replace the Line at Path
try newLine.write(to: fileURL, atomically: false, encoding: .utf8)
This will Append The Data with The Existing Data as New Line
try newLine.appendToURL(fileURL: path!)