How to append fast updating strings to file in swift

后端 未结 2 420
没有蜡笔的小新
没有蜡笔的小新 2021-01-26 08:04

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

相关标签:
2条回答
  • 2021-01-26 08:31

    Use seekToEndOfFile

    let myHandle = FileHandle.init(forWritingAtPath: fileUrl.path)
    
    myHandle.seekToEndOfFile 
    
    myHandle.write(strTowrite.data(using: String.Encoding.utf8)!)
    
    myHandle.closeFile()
    
    0 讨论(0)
  • 2021-01-26 08:36

    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!)
    
    0 讨论(0)
提交回复
热议问题