1

How can I Cache JSON from API ?

i Fetch the JSON from the API & Parse the JSON data. These can be done with the help of Alamofire & ObjectMapper and this my way to do this this my request function

Alamofire.request(URL(string: baseurl + serviceName) !,
    method: .post,
    parameters: parameters,
    encoding: createEncoding(serviceName: serviceName),
    headers: createHeaders(serviceName: serviceName))
  .responseJSON {
    (response: DataResponse < Any > ) in
    if let status = response.response ? .statusCode {
        print("URL: \(baseurl + serviceName)")
        print("request \(String(describing: NSString(data: (response.request?.httpBody)!, encoding: String.Encoding.utf8.rawValue)))")
        let data = response.data
        let responseStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) !as String
        print("response \(responseStr)")
        // String(data: response.request?.httpBody!, encoding: String.Encoding.utf8) as String!
        switch (status) {
          case 200:
            do {
              if let jsonArray =
                try JSONSerialization.jsonObject(with: data!, options: []) as ? [
                  [String: AnyObject]
                ] {
                  let genericArray = Mapper < RS > ().mapArray(JSONArray: jsonArray)
                  let arr = [RS](JSONArray: jsonArray)
                  let base = RS()
                  base!.genericArray = arr
                  print(genericArray)
                  callBack_Handler(base!)
                } else if
              let genericResponse = RS(JSONString: responseStr) {
                callBack_Handler(genericResponse)
              }

            } catch {
              print("Error deserializing JSON: \(error)")

            }

and this mapping model function import ObjectMapper

Alamofire.request(URL(string: baseurl + serviceName) !,
    method: .post,
    parameters: parameters,
    encoding: createEncoding(serviceName: serviceName),
    headers: createHeaders(serviceName: serviceName))
  .responseJSON {
    (response: DataResponse < Any > ) in
    if let status = response.response ? .statusCode {
        print("URL: \(baseurl + serviceName)")
        print("request \(String(describing: NSString(data: (response.request?.httpBody)!, encoding: String.Encoding.utf8.rawValue)))")
        let data = response.data
        let responseStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) !as String
        print("response \(responseStr)")
        // String(data: response.request?.httpBody!, encoding: String.Encoding.utf8) as String!
        switch (status) {
          case 200:
            do {
              if let jsonArray =
                try JSONSerialization.jsonObject(with: data!, options: []) as ? [
                  [String: AnyObject]
                ] {
                  let genericArray = Mapper < RS > ().mapArray(JSONArray: jsonArray)
                  let arr = [RS](JSONArray: jsonArray)
                  let base = RS()
                  base!.genericArray = arr
                  print(genericArray)
                  callBack_Handler(base!)
                } else if
              let genericResponse = RS(JSONString: responseStr) {
                callBack_Handler(genericResponse)
              }

            } catch {
              print("Error deserializing JSON: \(error)")

            }

I will populate the parsed data in the Table View. It works when the user is in Online. How can I cache the data to show it when the user is offline?

Mehdi
  • 717
  • 1
  • 7
  • 21
  • Two options I use are: Save the json file locally at the same time as fetching the data and the other is to write it to a data base of some kind that you over write if you have network connection. I check for network connectivity before running any calls to the internet and if no connectivity the data is fetched from the cached data that way. – MwcsMac Feb 20 '20 at 15:34
  • Not know the actual use-case but if you want to cache your data until the app the is in running state then you can create dataSources for your models listing i.e. if you are dealing with chat then there is a possible datasource named "ChatDataSource" that will maintain your chats once fetched till the app is not closed. If you cache data even after the app has terminated then you should use files or database and can store it in userDefaults if the data is small in size. – Najeeb ur Rehman Feb 23 '20 at 20:09

0 Answers0