Created
August 22, 2016 14:34
-
-
Save bittz/7c516fc9075015d05d83e90bf972fbeb to your computer and use it in GitHub Desktop.
Custom NSURLCache for web services which don't provide expiration info.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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