0

Swift 4: As you know, here is how to read or write data from & to text file in Documents Directory with Swift:

        let DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)

        let fileURL = DocumentDirURL.appendingPathComponent("Test").appendingPathExtension("txt")
        print("FilePath: \(fileURL.path)")

        let writeString = "Add string"

        do {
            // Write to the file

            try writeString.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)

        } catch let error as NSError {

            print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)

        }

        var readString = "" // Used to store the file contents

        do {

            // Read the file contents

            readString = try String(contentsOf: fileURL)

        } catch let error as NSError {

            print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription)

        }

        print("File Text: \(readString)")

It will write Add string to the Test.txt file.

The next time when I change "Add string" to "Add some other string.", the Test.txt file will be changed to Add some other string.

Which means that "Add string" will be replaced by "Add some other string.". But I would like to add these two strings to the Test.file incrementally, so that the Test.txt file will contain: Add string, Add some other string.

Is there any way to make it happen? Thanks.

Vincent
  • 486
  • 6
  • 20

0 Answers0