user2636197
user2636197

Reputation: 4122

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"]
self.tableView.reloadData()

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

Upvotes: 3

Views: 1578

Answers (2)

hlc
hlc

Reputation: 1

Swiftlycache can be used for data caching. You can directly cache the data that complies with the codable protocol. It's very convenient. If you need it, you can try it https://github.com/hlc0000/SwiftlyCache

Upvotes: 0

Sahil Mahajan
Sahil Mahajan

Reputation: 3990

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
}

Upvotes: 3

Related Questions