How to append fast updating strings to file in swift

做~自己de王妃 提交于 2019-12-31 05:29:11

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!