我一直在尝试使用 AFNetworking 实现缓存,以便我缓存的 JSON 可以离线加载。我以不同的方式尽力而为,我根本无法使缓存工作。我不知道我在这里错过了什么..
这是我的 AppDelegate
中的代码:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
var cache :NSURLCache = NSURLCache(memoryCapacity: 4*1024*1024, diskCapacity: 32*1024*1024, diskPath: "app_cache")
NSURLCache.setSharedURLCache(cache)
return true
}
这也是我用来获取 JSON 的代码:
let manager = AFHTTPRequestOperationManager()
manager.requestSerializer = AFJSONRequestSerializer()
manager.requestSerializer.cachePolicy = NSURLRequestCachePolicy.ReturnCacheDataElseLoad
manager.GET("http://api.androidhive.info/json/movies.json", parameters: nil, success: { (operation, responseObject) -> Void in
if let j: AnyObject = responseObject, let mediaObjects = j.valueForKeyPath("image") as? NSArray {
self.imageArray = mediaObjects as! [String]
}
self.myCollectionView.reloadData()
println("success")
}, failure: { (operation, error) -> Void in
})
所以在失败 block 中我想加载缓存数据但我不知道我错过了什么? 请提供工作代码,缓存是一个很大的话题,我找不到一个完整的工作示例!
最佳答案
伙计,我不太了解 swift 但只要我知道你要做的就是:
首先,从你的get中捕获返回的数据,然后保存到NSCachedURLResponse中。在 Objective-C 中会是这样的:
NSCachedURLResponse *cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:operation.response data:operation.responseData];
[[NSURLCache sharedURLCache] storeCachedResponse:cachedResponse forRequest:urlRequest];
在那之后,如果您的申请抛出错误,您将恢复之前为该 URL 保存的数据。
NSData *data = [[[NSURLCache sharedURLCache] cachedResponseForRequest:urlRequest] data];
希望对您有帮助。
关于ios - 使用 AFNetworking 加载离线缓存的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31572050/