AwesomeCache icon indicating copy to clipboard operation
AwesomeCache copied to clipboard

Load from cache if network connection fail

Open flowbe opened this issue 10 years ago • 2 comments

Hello,

Is it possible to load object from cache only if the request can't be executed ?

Thanks

flowbe avatar Mar 15 '15 11:03 flowbe

I am planning to support something like this. However, I am not sure about how the API for this should look like.

There are two options:

  • The method returns the cached object immediately, then tries to load the object from the provided url and invokes a completion block on success or failure.
  • The method calls an update closure twice: once when the object is initially loaded from the cache and once when the network request is finished.

In the meantime, here's a quick prototype that should work for you:

let key = "key"

if let o = cache[key] {
  // do something with cached o
}

// reload from network
let url = NSURL(string: "http://example.com/api")
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url) { (data, response, error) in
  if let e = error {
    println("could not load object from network: \(e)")
  } else {
    cache[key] = data
    // use newly cached object
  }
}

aschuch avatar Mar 17 '15 07:03 aschuch

Works fine ! Thanks

Please tell me if you do an update to natively support this

flowbe avatar Mar 24 '15 18:03 flowbe