-1

I am storing in a json file some user credentials (email, password, nickname). When I open the app on simulator and create multiple test accounts all works perfectly.

import Foundation

var users: [UserCredentials] = []

func save (email: String, password: String, nickname: String) {
    let newUsers = UserCredentials(email: email, password: password, nickname: nickname)
    users.append(newUsers)
    
    let encoder = JSONEncoder()
    encoder.outputFormatting = .prettyPrinted
    
    do {
        let data = try encoder.encode(users)
        let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("users.json")
        print(url.path)
        try data.write(to: url)
    } catch {
        print("Error encoding JSON: \(error)")
    }
}

The issue comes up when I reset the app and I type a new testuser. The json file resets instead of loading the testusers I saved before. Is there a way where the users stay saved in a file even when I restart the simulator?

Before reset:

    ```JSON
    [
  {
    "email" : "beforereset@yahoo.com",
    "nickname" : "beforereset12",
    "password" : "test1234A"
  },
  {
    "email" : "beforereset1@yahoo.com",
    "nickname" : "beforereset123",
    "password" : "test1234A"
  }
]

    ```

After reset:

```JSON
[
  {
    "email" : "afterreset@yahoo.com",
    "nickname" : "afterreset12",
    "password" : "1234testA"
  }
]
```

Where are the beforereset emails?

  • What do you meant by *The problems comes up when I reset the app*? You meant you delete app and re-install again? – Fahim Parkar Feb 15 '23 at 13:08
  • when I simply rerun the app on xcode – axandrei1234 Feb 15 '23 at 13:14
  • No pictures of text please. – matt Feb 15 '23 at 13:24
  • 1
    Please read the answer below first before continuing with your approach. But answering your question directly: when you launch the app, do you then fill your array first by reading out the contents? Or do you just start off with an empty array, save that when a new entry comes in and thus overwrite your old file? – JanMensch Feb 15 '23 at 13:26
  • I am starting with an empty array. Now I understand what I'm doing wrong. But I don't know how to fix it. – axandrei1234 Feb 15 '23 at 13:32
  • I already told you in my answer. Read from the file into users before writing users to the file. – matt Feb 15 '23 at 13:43

1 Answers1

2

This line

try data.write(to: url)

...deletes the existing file's contents and replaces them. Thus every time save runs, the previous contents of the file are lost. (Unless of course you read those contents from the file into users before saving. But no code that you have shown us does that, so I have to conclude that you're not doing it at all.)

Where are the beforereset emails?

Gone. You erased them.

matt
  • 515,959
  • 87
  • 875
  • 1,141