问题
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 try to.
func startAccel(fileName: String, fileURL: URL) ->Void{ //Starting accelerometer
motionManager.accelerometerUpdateInterval = 1.0 / Double(hz) //determines refresh speed
motionManager.startAccelerometerUpdates(to: OperationQueue.current!){ (data, error) in
if let myData = data{
do{
let newLine = "Accelerometer, \(myData.acceleration.x), \(myData.acceleration.y),\(myData.acceleration.z)\n"
try newLine.write(to: fileURL, atomically: false, encoding: .utf8)
try print(String(contentsOf: fileURL, encoding:.utf8))
}catch{
print("yeah that didn't work sorry bub")
}
}
}
}
This code overwrites the file every time newLine.write() is called, and there is no append option for that function. How can I append the sensor output to the file as it collects it?
回答1:
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!)
回答2:
Use seekToEndOfFile
let myHandle = FileHandle.init(forWritingAtPath: fileUrl.path)
myHandle.seekToEndOfFile
myHandle.write(strTowrite.data(using: String.Encoding.utf8)!)
myHandle.closeFile()
来源:https://stackoverflow.com/questions/49863062/how-to-append-fast-updating-strings-to-file-in-swift