我正在尝试使用 Alamofire 缓存,所以我想要的行为是第一次从网络加载,下次如果数据存在于缓存中则返回它而不发出更多请求......在我考虑过期之后...
我的代码总是返回响应 nil...对此有什么建议吗?谢谢
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.URLCache = NSURLCache.sharedURLCache()
config.requestCachePolicy = NSURLRequestCachePolicy.ReturnCacheDataElseLoad
let manager = Alamofire.Manager(configuration: config)
manager.request(.GET, url, parameters: parameters, encoding: .URL, headers: ["Token":LocalStorage.read("token") as! String, "Version":"2"]).responseJSON { (response) in
if let json = response.result.value
{
if response.response?.statusCode == 200
{
completionHandler(parser.parseSwifty(JSON(json)), nil)
}
else
{
completionHandler(nil, serverErrorMessage)
}
}
else
{
completionHandler(nil, networkErrorMessage)
}
}
最佳答案
所以...我解决了这个问题: 在我的 NetworkHelper 中,我添加了一个计算属性,如下所示:
static let manager: Manager = {
let memoryCapacity = 100 * 1024 * 1024; // 100 MB
let diskCapacity = 100 * 1024 * 1024; // 100 MB
let cache = NSURLCache(memoryCapacity: memoryCapacity, diskCapacity: diskCapacity, diskPath: "shared_cache")
let configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = ["Token":LocalStorage.read("token") as! String, "Version":"2"]
configuration.requestCachePolicy = .ReturnCacheDataElseLoad // this is the default
configuration.URLCache = cache
return Manager(configuration: configuration)
}()
当我必须检索一些数据时:
self.manager.request(.GET, url, parameters: parameters, encoding: .URL)
.response { (request, response, data, error) in
debugPrint(request)
debugPrint(response)
debugPrint(error)
}.responseJSON......
我还编写了一个函数来预加载一些数据,如下所示:
static func preloadGetRequest(url : String, parameters: Dictionary<String, String>?)
{
self.manager.request(.GET, url, parameters: parameters, encoding: .URL)
.response { (request, response, data, error) in
debugPrint(request)
debugPrint(response)
debugPrint(error)
}
}
试着让我知道:)
关于swift - 尝试使用 Alamofire 缓存但没有结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39780553/