Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom NSURLCache for web services which don't provide expiration info.
import Foundation
class CustomURLCache: NSURLCache {
let createdAtKey = "CreatedAt"
override func cachedResponseForRequest(request:NSURLRequest) -> NSCachedURLResponse? {
let cachedResponse = expiredCachedResponseForRequest(request)
if cachedResponse == nil {
removeCachedResponseForRequest(request)
}
return cachedResponse
}
override func storeCachedResponse(cachedResponse: NSCachedURLResponse, forRequest request: NSURLRequest) {
var newUserInfo = cachedResponse.userInfo ?? [NSObject : AnyObject]()
if let expiredCachedResponse = expiredCachedResponseForRequest(request),
userInfo = expiredCachedResponse.userInfo,
createdAt = userInfo[createdAtKey] as? NSDate {
newUserInfo[createdAtKey] = createdAt
} else {
newUserInfo[createdAtKey] = NSDate()
}
let newCachedResponse = NSCachedURLResponse(response: cachedResponse.response, data: cachedResponse.data, userInfo: newUserInfo, storagePolicy: cachedResponse.storagePolicy)
super.storeCachedResponse(newCachedResponse, forRequest: request)
}
func expiredCachedResponseForRequest(request:NSURLRequest) -> NSCachedURLResponse? {
var cachedResponse: NSCachedURLResponse? = nil
if let actualCachedResponse = super.cachedResponseForRequest(request),
userInfo = actualCachedResponse.userInfo,
createdAt = userInfo[createdAtKey] as? NSDate {
if createdAt.timeIntervalSinceNow > -3600 {
cachedResponse = actualCachedResponse
}
}
return cachedResponse
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.