I am using Alamofire to perform all network API calls to get a bunch of different JSON files (depending on the view the user is on).
Some of the JSON gets user profile details, some user settings, some data for a tableview.
I am using the below
let postParameters: [String: AnyObject] = ["apiKey":"\(Constants.Variables.apiKey)",
"domain":"\(Constants.Variables.apiDomain)",
"authToken":"\(authToken)",
"password":"\(password)",
"from":"\(from)",
"to":"\(to)"]
Alamofire.request(Router.GetActivities(postParameters))
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.responseJSON { response in
if response.result.isSuccess {
let responseJSON = JSON(response.result.value!)
}
}
and I have a router set up
enum Router: URLRequestConvertible {
static let baseURLString = "\(Constants.APIPath.URL)"
static var OAuthToken: String?
case GetActivities([String: AnyObject])
var method: Alamofire.Method {
switch self {
case .GetActivities:
return .GET
}
}
var path: String {
switch self {
case .GetActivities(_):
return "/activity.php/get"
}
}
var URLRequest: NSMutableURLRequest {
let URL = NSURL(string: Router.baseURLString)!
let mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path))
mutableURLRequest.HTTPMethod = method.rawValue
if let token = Router.OAuthToken {
mutableURLRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
}
switch self {
case .GetActivities(let parameters):
return Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: parameters).0
}
}
}
Each time I load any view that has a tableview on it (say view2), the app re-fetches the data from the API. The tableview is part of a navigation controller and going to the view re-fetches the data but going back to the view does not.
Example:
- Case 1: view1 -> view2 = re-fetch JSON every time regardless
- Case 2: view2 -> view3 = load details of table cell that was tapped
- Case 3: view3 -> view2 = does not re-fetch JSON
- Case 4: view2 -> view1 = I am guessing view2 is no longer needed so it is dismissed
I would like that going from view1 -> view2 does not need to re-fetch the data each time if it has it in cache and the only way to refresh is either after the user logs back in to the app or using the pull to refresh feature.
I am new to Swift development so any guidance on how to cache JSON using either Alamofire or Haneke is greatly appreciated.
Haneke looks promising but I am not sure how to implement it using Alamofires post parameters.
Many thanks.