Alex Cauthen
Alex Cauthen

Reputation: 517

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!

Upvotes: 0

Views: 1230

Answers (2)

Noman Haroon
Noman Haroon

Reputation: 193

Make sure to add these two keys in info.plist and set them to "YES"

Supports opening documents in place

Application supports iTunes file sharing

Upvotes: 0

Eric Aya
Eric Aya

Reputation: 70098

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)

Upvotes: 1

Related Questions