I am making a HTTP get request in swift where I am getting an outdated response for some reason..I have compared the response in Postman with the one I printed in the Xcode and I'm getting this..
Response Headers in Postman:
Response Headers printed in Xcode Console:
see the sections highlighted in green, both the calls are made at the same time. This is a live API of my project and as there is no change in the current live data I am not showing JSON response. But as you can see in the response headers, the value for field "Date" in both Postman and Xcode is different.. When I do it in Postman, it is giving me new response every time. But in Xcode I'm getting the same response all day. I don't know why This is happening. And after erasing the contents of simulator (or deleting the app from simulator) and reinstalling the project again it gave me a new updated response. But it's again repeated...
Code in RequestManager Class:
import Foundation
class RequestManager {
class func callTheGetAPI(urlString: String, closure: @escaping (Data?)->Void) {
let url = URL.init(string: urlString)
var urlRequest = URLRequest(url: url!)
urlRequest.httpMethod = "GET"
urlRequest.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let dataTask = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
if (error != nil) {
print(error!.localizedDescription)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse!.allHeaderFields)
closure(data)
}
}
dataTask.resume()
}
}
code in my ViewController:
override func viewDidLoad() {
super.viewDidLoad()
getRecommendedData()
}
func getRecommendedData() {
let url = APIManager.API_01
RequestManager.callTheGetAPI(urlString: url, closure: { response in
do {
if (try JSONSerialization.jsonObject(with: response!, options: .mutableContainers) as? [[String : Any]]) != nil{
// print(json)
}
} catch let error {
print(error.localizedDescription)
}
})
}
This is all I have guys.. If anyone knows what's happening or if I'm doing something wrong.. Please help..
Replace below line
var urlRequest = URLRequest(url: url!)
With
var urlRequest = URLRequest(url: url!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 60)
From the documentation reloadIgnoringCacheData: Specifies that the data for the URL load should be loaded from the origin source. No existing local cache data, regardless of its freshness or validity, should be used to satisfy a URL load request.
By default it uses caches.