0

As an exercise, I'm trying to write a logging class that logs strings to a text file. I've got my application to write and read from the file. However, if I try to log multiple times it seems to only pick up the most recent log.

Attempt

writing

private let file = "logfile.txt"

func write(text: String) {

    let path = getDocumentsDirectory()

    do {
        try text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding)
    }
    catch let error {
        print("error: \n \(error)")
    }
}

reading

func read() {

    let path = getDocumentsDirectory()

    do {
        let text2 = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding)

        print("From Log: \n \(text2)")
    }
    catch let error {
        print("error: \n \(error)")
    }


}

func getDocumentsDirectory() -> String {
    guard let dir : NSString = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first else {
        return ""
    }
    let documentsDirectory : String = dir.stringByAppendingPathComponent(file)
    return documentsDirectory
}

Result

When I try to read my file I only get the last line saved.

Question

If my goal is to endlessly append new logs to a file, and to read the log file in bulk. What changes to my code do I need to make?


more details:

I'm writing to the file on application load:

Logger.shared.write("instance one writes")
Logger.shared.write("instance one writes again")
Logger.shared.write("instance one writes yet again") 

and then attempting to read:

Logger.shared.read()

output:

From Log:
instance one writes yet again

Dan Beaulieu
  • 19,406
  • 19
  • 101
  • 135
  • Possible duplicate of [writeToFile in OSX, appending to the file?](http://stackoverflow.com/questions/4626697/writetofile-in-osx-appending-to-the-file) – jtbandes Jan 07 '16 at 03:41
  • On the contrary, you are using exactly the same method (`writeToFile(_:atomically:encoding:)`) which produces exactly the same problem, and I would recommend exactly the same solution (`NSFileHandle`). The language difference is hardly worth noting, especially since the accepted answer provides a place to look in the docs, and not actual code. – jtbandes Jan 07 '16 at 03:48
  • Here is another similar question if you like: http://stackoverflow.com/questions/4779877/how-to-write-in-append-mode-for-text-file – jtbandes Jan 07 '16 at 03:49
  • @jtbandes I can't find a single example of someone using NSFileHandle in Swift the way it is in your two posts. .fileHandleForWritingAtPath is unavailable in Swift. – Dan Beaulieu Jan 07 '16 at 04:14
  • It's an initializer rather than a static method; the Obj-C and equivalent Swift syntax are given in the documentation here: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSFileHandle_Class/#//apple_ref/occ/clm/NSFileHandle/fileHandleForWritingAtPath: – jtbandes Jan 07 '16 at 04:16

1 Answers1

2

The writeToFile(_:atomically:encoding:) method provided by Foundation replaces the contents of the given file. There are several ways of appending to files:

Community
  • 1
  • 1
jtbandes
  • 115,675
  • 35
  • 233
  • 266
  • I appreciate your time, sorry for being difficult. – Dan Beaulieu Jan 07 '16 at 04:29
  • No problem. Apologies for curtness — it's often hard to judge when it's worth rewriting answers for Swift, because these APIs are identical in functionality to the Obj-C ones (just a different syntax), so good answers often exist already in the wrong language. For every Swift app developer's sake, I recommend they gain at least a little [familiarity with Obj-C](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html) — the ability to read *just enough* Obj-C to translate to Swift is immensely useful. – jtbandes Jan 07 '16 at 04:34
  • I definitely plan on it, I'm still taking Swift classes right now so the Cocoa framework is all new to me. Thanks again. – Dan Beaulieu Jan 07 '16 at 04:36
  • I would recommend browsing the articles on http://nshipster.com/ — almost all their code samples are in both Obj-C and Swift so you can compare them easily. And you'll learn some things about Cocoa at the same time :) – jtbandes Jan 07 '16 at 04:43