Richa Srivastava
Richa Srivastava

Reputation: 492

Storing array of data in cache iOS Swift

In my app, i get the menu of the app through a web service. It around 423 number of records which changes rarely. What I need is to cache this record in the app after first time login and use the cached data. If there is any changes in the menu database then only it should refresh the menu content from web service again. I am not very sure how i can achieve this. Currently I store all the records in an array of menu class and use directly, which is very time consuming as we are hitting the service call again and again for similar record. I am new to iOS development so any suggestions are most welcome.

Thanks!

Upvotes: 1

Views: 2736

Answers (1)

brandonscript
brandonscript

Reputation: 73014

Store the data in one of NSUserDefaults (if this is infrequent, but permanent config data), or NSCache (for ephemeral data), or CoreData (for permanent, performance-dependent data).

Load this cached data on app launch; if the cached data doesn't exist, retrieve it from your web service/API.

If you're not concerned with the data being up to date immediately after you change the menu content, use something like the Cache-Control header to set an invalidation time period (details). If you do want to ensure that the menu updates as soon as a new remote version is available, then you'll need to set up a versioning system where your app makes an API call to check the version of the menu and update if required.

Example scenario:

  1. App launch
  2. Load menu content from NSUserDefaults/CoreData/NSCache
  3. Asynchronously check API for menu version
  4. If new version of menu exists, asynchronously download and refresh the menu view
  5. Save updated version of menu back to NSUserDefaults/CoreData/NSCache.

Upvotes: 1

Related Questions