AwesomeCache
AwesomeCache copied to clipboard
Load from cache if network connection fail
Hello,
Is it possible to load object from cache only if the request can't be executed ?
Thanks
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
}
}
Works fine ! Thanks
Please tell me if you do an update to natively support this