0

I am trying to create a file and update the file by adding a string to the end each time i hit save button. However, everytime i hit save it creates a new file (overwrites) with the latest string. My code is below, how can i fix it? please help!

func pathToDocsFolder() -> String {

    let pathToDocumentsFolder =NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString

    return pathToDocumentsFolder.stringByAppendingPathComponent("/log.csv")
}  

@IBAction func saveSample(sender: AnyObject) {

    let string = LabelText + ";" + SampleNoOne.text! + ";" + fromOne.text! + ";" + toOne.text! + ";" + casingBlowsOne.text! + ";"

    let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!

    let filemanager = NSFileManager.defaultManager()


    if filemanager.fileExistsAtPath(pathToDocsFolder()){
        filemanager.createFileAtPath(pathToDocsFolder(), contents: data, attributes: nil)
    }


    let fileHandle = NSFileHandle.init(forUpdatingAtPath: pathToDocsFolder())

    fileHandle!.seekToEndOfFile()
    fileHandle!.writeData(data)
    fileHandle!.closeFile()
James Zaghini
  • 3,895
  • 4
  • 45
  • 61
Gigi
  • 1
  • Why do you create the file if it exists? I think you mean to only create the file if it doesn't exist. – rmaddy Jun 23 '16 at 02:57

2 Answers2

0

update:

if filemanager.fileExistsAtPath(pathToDocsFolder()){
     filemanager.createFileAtPath(pathToDocsFolder(), contents: data, attributes: nil)
}

to:

if filemanager.fileExistsAtPath(pathToDocsFolder()) == false {
        filemanager.createFileAtPath(pathToDocsFolder(), contents: data, attributes: nil)
    }
jimmy
  • 149
  • 1
  • 6
0

As you want to append in the file use "forWritingAtPath" instead of "forUpdatingAtPath" Replace the following line:

let fileHandle = NSFileHandle.init(forUpdatingAtPath: pathToDocsFolder())

With

let fileHandle = NSFileHandle.init(forWritingAtPath: pathToDocsFolder())

Also make sure your condition to check existing file is correct.

gagan sharma
  • 256
  • 1
  • 4
  • 18