Persisting User Input Data in SwiftUI

I'm developing an application using SwiftUI and SwiftData. The app includes a pricing section, and I'd like it to have an initial default value for pricing. Additionally, when updating the app on the App Store, I also want to update the prices. However, I'd like users to have the option to create their own prices if they don't want to use the ones I suggest. I want to save these prices obtained from the user because I'll be using these values for some operations later on.

I'm wondering how to achieve this. Should I use SwiftData or UserDefaults for managing the data, or should I save the prices to a JSON file? If I opt for saving to a JSON file, would it be possible to update the JSON file when updating the app? Please feel free to ask any questions. Thank you in advance for your responses.

Replies

So, if I understand correctly, you want to use (and save) 2 pricing tables:

  • the default one that may be updated when app is updated
  • the user's one if he/she has defined. And you want user to be able to keep it if desired.

What is the size of these pricing tables ?

If they are not too large (let's say, less than 1000 items), I would:

  • create a dictionary with the price list

  • include the default pricing in a JSON and include it in the project resources

  • if user creates a price list, save it in User.defaults as another JSON (containing only the prices that were modified).

  • When you load the app, you first decode the default pricing from the JSON

  • Then you read user defaults to see if some price has to be superseded by a user price. You update the price dictionary for those keys (product name)

Doing so will allow:

  • add new prices in the JSON when you create a new release or modify some default prices
  • work with whatever number of prices modified by user (even 0)
  • preserve user prices. When uploading new release, you may ask user if he wants to keeps its prices or update with new defaults. If so, you should clear those user defaults.

If several 1000 of items, SwiftData may be a better choice.

This may help you create the JSON from the initial dictionary: https://www.tutorialspoint.com/convert-a-dictionary-to-json-in-swift

Please tell if anything is not clear enough.

  • Thank you very much for your reply. I want the user to enter only 5 prices. I forgot to mention above that if the user wants to enter prices himself, I want to synchronise these prices with iCloud. Can I synchronise UserDefaults? @Claude31

Add a Comment

With this scheme, user can create its own articles and prices as well (just need to check that item is not a duplicate in that case).

What do you want exactly to save in iCloud ?

To save in iCloud: https://www.hackingwithswift.com/example-code/system/how-to-store-userdefaults-options-in-icloud