This is how you can Append A new Line to a file at specific URL instead of Writing it (as Writing will Replace the previous stored content)
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: NSData Extension
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
/// if want to add a New Line
let newLine = "your content\n"
/// if want to append just next to previous added line
let newLine = "your content"
do
{
//save
try newLine.appendToURL(fileURL: path!)
}
catch
{
//if error exists
print("Failed to create file")
print("\(error)")
}
Update this is how I am using this function
//MARK: Usage
func updateCsvFile(filename: String) -> Void
{
//Name for file
let fileName = "\(filename).csv"
let path1 = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let documentDirectoryPath:String = path1[0]
//path of file
let path = NSURL(fileURLWithPath: documentDirectoryPath).appendingPathComponent(fileName)
//Loop to save array //details below header
for detail in DetailArray
{
let newLine = "\(detail.RecordString)\n"
//Saving handler
do
{
//save
try newLine.appendToURL(fileURL: path!)
showToast(message: "Record is saved")
}
catch
{
//if error exists
print("Failed to create file")
print("\(error)")
}
print(path ?? "not found")
}
//removing all arrays value after saving data
DetailArray.removeAll()
}