如何在swift中将快速更新字符串附加到文件中 [英] How to append fast updating strings to file in swift

查看:373
本文介绍了如何在swift中将快速更新字符串附加到文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当传感器在方法中更新时,我想将传感器数据写入文件。我需要在更新时附加数据,但是当我尝试时,我的文件会覆盖最后一个传感器输出。

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")
            }
        }
    }
}

此代码每隔ti覆盖一次文件我调用了newLine.write(),该函数没有附加选项。如何在收集文件时将传感器输出附加到文件中?

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?

推荐答案

只需尝试使用此

//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,

These Extension will Append Your NewLine Which you exactly looking for to Do,

这只会替换路径上的Line

try newLine.write(to: fileURL, atomically: false, encoding: .utf8)

这将使用现有数据作为新行附加数据

try newLine.appendToURL(fileURL: path!)

这篇关于如何在swift中将快速更新字符串附加到文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆