我想在传感器在方法中更新时将传感器数据写入文件。我需要在更新时附加数据,但是当我尝试时,我的文件会覆盖最后一个传感器输出。
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")
}
}
}
}
每次调用newLine.write()时,此代码都会覆盖该文件,并且该函数没有附加选项。如何在收集文件时将传感器输出附加到文件中?
答案 0 :(得分:0)
使用seekToEndOfFile
let myHandle = FileHandle.init(forWritingAtPath: fileUrl.path)
myHandle.seekToEndOfFile
myHandle.write(strTowrite.data(using: String.Encoding.utf8)!)
myHandle.closeFile()
答案 1 :(得分:0)
尝试使用此
//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)
}
}
}
用法:
try newLine.appendToURL(fileURL: path!)
这些扩展将附加您正好想要的NewLine,
这只会替换路径中的行
try newLine.write(to: fileURL, atomically: false, encoding: .utf8)
这将使用现有数据附加数据作为新行
try newLine.appendToURL(fileURL: path!)