0

I'm super new to Swift 3 and Xcode. I've looked all over trying to find a code to Read and write to a file using Swift. However every code I found only writes to the file but replaces that text every time it's written.

Can someone show me a code to write the current Date/time to a file when a button is pressed, but have it so that it doesn't write over all the other times logged. I need it to append to the file so I can log date and Time every time this button is pressed. Thanks

Once again I'm using Xcode 9.3 so I need the answer to this in Swift 3 or Swift 4. The other answer I don't know how to follow. I'm new to Swift 3 I need someone to explain how I can use this Write to File In kinda a step by step approach. I mean I know the code basic's but I never used Read write to file before. I'm trying to have this save text from a label which shows the current time, to a file, that way it shows a log of all the times the button was pushed. It's for a Medication tracker App. So every time I take my med I click this button and I want it to write the current time to a file. Then later I click the button and it add's the current time to the file without writing over the last time I clicked the button. I hope this helps people to understand what it is I'm trying to accomplish.

John Martin
  • 443
  • 1
  • 4
  • 7
  • If you are new to Swift start with the current version 4.1 – vadian May 02 '18 at 11:10
  • Obj-C way: https://stackoverflow.com/questions/4779877/how-to-write-in-append-mode-for-text-file check out the logic and translate it to Swift. the key point is `[myHandle seekToEndOfFile]` – NeverHopeless May 02 '18 at 11:11
  • Create an empty array: `var dateArray = [Date]()` and when button pressed: `let newDate = Date()` `if let savedDates = UserDefaults.standard.array(forKey: "Dates") as? [Date] { dateArray = savedDates }` `dateArray.append(newDate)` `UserDefaults.standard.set(dateArray, forKey: "Dates")` – rbaldwin May 02 '18 at 11:17

0 Answers0