How to write / read a txt file with Swift 2?

Sorry to ask such a basic question. I am starting to write programs on MacOS and iOS. It looks like Google does not help me a lot.

I know how to find the document directory in iOS (cf. iOS apprentice, tutorial 2).
Now, how can I add lines to my text file ? How can I read them back later ?

Regards,
Gilbert

Hi Gilbert,

Here is a link to Stackoverflow which shows an example of what you may be trying to accomplish. I would have pasted in here; but I would like to give credit to the person who wrote the sample.

Reading and Writing Data to a Text File in Swift 2

Here’s something from project I was working on last week.

Get the path:

    let cachesDirectory = NSURL(string:NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!)
    let vertexAndNormalsPath = (cachesDirectory!.URLByAppendingPathComponent("\(vertexAndNormalsFilename).plist")).absoluteString

Note this uses the /Library/Caches directory. If you can create the asset again and don’t want it in backups, this is the place to put it.

Then when the app is starting:

    let fileManager = NSFileManager.defaultManager()
    if fileManager.fileExistsAtPath(vertexAndNormalsPath) {
        
        vertexAndNormalsData = NSArray(contentsOfFile: vertexAndNormalsPath) as! [GLfloat]
        
    } else {
    
        // populate vertex/normal and index data, save to cache
        parseAndStore()
    }

I’ll leave out the part where the raw data files are parsed in parseAndStore, but here’s how they are stored:

    (vertexAndNormalsData as NSArray).writeToFile(vertexAndNormalsPath, atomically: false)

A couple of different approaches show there’s still no getting away from dropping back to NSString or NSArray for some functionality. I looked for a “pure” Swift way to do it but didn’t find one.