Search code examples
iosswiftcsvnsfilemanagernsfilehandle

Swift: Creating a csv file in Documents Directory


I am creating a registration form application. The registration form data will be saved in a CSV file. I need to create a csv file in the documents directory and be able to write to it. I'm pretty new to Swift so I'm having a bit of trouble. This is what I've got so far.

var fileManager = NSFileManager.defaultManager()
var fileHandle: NSFileHandle

@IBAction func submitForm(sender: AnyObject) {
    mySingleton.filename = mySingleton.filename + ".csv"
    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
    let filePath = documentsPath + mySingleton.filename

    if !fileManager.fileExistsAtPath(mySingleton.filename) {
        fileManager.createFileAtPath(filePath, contents: nil, attributes: nil)
        fileHandle = ...
    }

}

Obviously the code I'm having trouble with is the FileHandle which is what allows to to modify the file. In objective-c it would look something like this:

fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:event];

Then obviously if I wanted to write to the file I could do something like this:

[fileHandle seekToEndOfFile];
[fileHandle writeData:[formData dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];

So I'm really only struggling with that one part. Thanks for the help!


Solution

  • In Swift, fileHandleForUpdatingAtPath has become an initializer of NSFileHandle, adopting the Swift naming convention of avoiding repetition and taking the end of the Objective-C method name, making it the parameter name:

    let fileHandle = NSFileHandle(forUpdatingAtPath: yourPath)