17

I set cache policy to request in Alamofire to ignore local cache.

Then I load a viewcontroller with network connection, then I disconnect network connection, kill the app and run it again.

Now no network available error is not shown(ie alamofire doesnt create nserror object) created, instead app runs as if the request succeeded getting data from cache obviously.And the odd thing is the when I tried to inspect the cached data using

NSURLCache.sharedURLCache().cachedResponseForRequest(request)

nil is returned eventhough the data was from cache ..

The only way I could prevent cached responses is perform NSURLCache.sharedURLCache().removeAllCachedResponses()

    let request = NSURLRequest(URL: NSURL(string: url)!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 100)

    Alamofire.manager.request(method, request, parameters:params)
    .responseJSON { (request, response, data, error) in
        if let anError = error {
            if anError.code == NSURLErrorNotConnectedToInternet {
                UIAlertView(title: "Alert", message: "No Network Connection Available", delegate: nil, cancelButtonTitle: "ok").show()
            }    

        } else if let data: AnyObject = data {
            println(NSURLCache.sharedURLCache().cachedResponseForRequest(request))
 //prints nil

    }

} 
}

What I want to do is load data from cache only if network connection is not available, something like limited offline mode.How to do this?

Sai Prasanna
  • 684
  • 1
  • 10
  • 25

3 Answers3

13

I'm using this way in a project and it's working:

let mutableURLRequest = NSMutableURLRequest(URL: SERVICEURL)
mutableURLRequest.HTTPMethod = "POST"

mutableURLRequest.HTTPBody = self.createJson()
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData

request(mutableURLRequest).validate().responseJSON{ response in...

Hope it helps.

Fábio Salata
  • 372
  • 11
  • 16
  • @HongZhou It's a convenience method of Alamofire. You can use it as `Alamofire.request(mutableURLRequest).validate().responseJSON‌​{ response in...` – Fábio Salata Aug 30 '16 at 17:21
  • @FábioSalata. can u please guide how to cache the data in swift3. I am working with alamofire. – Uma Madhavi May 15 '17 at 10:01
  • @FábioSalata Can you please help me how to cache the data in a swift using Alamofire for the particular time limit and get from cached data before service call? – Nikunj Kumbhani Nov 12 '18 at 05:53
8

Thanks to @FábioSalata I solved my problem like this.

 var req = URLRequest(url: URL(string: "<URL>")!)
 req.httpMethod = "GET"
 req.setValue("application/json", forHTTPHeaderField: "Content-Type")
 req.setValue("<Auth KEY>", forHTTPHeaderField:"Authorization" )
 req.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData

 Alamofire.request(req).validate().responseJSON { response in ...
Ahmet Sina Ustem
  • 1,090
  • 15
  • 32
5

ReloadIgnoringLocalAndRemoteCacheData is not implemented.

https://developer.apple.com/reference/foundation/nsurlrequestcachepolicy/1408722-reloadignoringlocalandremotecach

http://nshipster.com/nsurlcache/

Update: Starting with iOS 13, NSURLRequest.CachePolicy.reloadRevalidatingCacheData and NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData are implemented. https://developer.apple.com/documentation/ios_ipados_release_notes/ios_13_release_notes

robinkunde
  • 1,005
  • 9
  • 12
  • It is now. https://developer.apple.com/documentation/ios_ipados_release_notes/ios_13_release_notes#see-also both NSURLRequest.CachePolicy.reloadRevalidatingCacheData and NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData. – SleepNot Nov 18 '19 at 06:25
  • Thanks! Updated my answer. – robinkunde Nov 19 '19 at 16:00