user2636197 user2636197 - 9 months ago 100
JSON Question

Swift cache tableview json data

I wonder if its possible to cache tableView JSON data?

In my VC I have this variable:

//Categories json data
var categories: JSON! = []

Then later inside a alamofire api call I get the json data and assign it like:

self.categories = JSON["catData"]

But is there any way to cache this data so I dont have to make a API call everytime?

Answer Source

You can create a singleton DataCache class where you can store all the data you want to cache. Prefer to store data inside a dictionary for specific key

class DataCache: NSObject {
    static let sharedInstance = DataCache()
    var cache = [String, AnyObject]()

Now in your api call, call this method

DataCache.sharedInstance.cache["TableViewNameKey"] = JSON["catData"]
self.categories = JSON["catData"] // Set this property for first time when you hit API

and in viewWillAppear(animated: Bool) method

if let lCategories = DataCache.sharedInstance.cache["TableViewNameKey"] {
    self.categories = lCategories