使用AFNetworking加载离线缓存的JSON [英] Load offline cached JSON using AFNetworking
问题描述
我一直在尝试使用AFNetworking实现缓存,因此我的缓存JSON将离线加载.我以不同的方式尽了最大的努力,我根本无法使缓存正常工作.我不知道我在这里想念什么.
I've been trying to implement caching using AFNetworking so my cached JSON will be loaded offline. i tried my best in different ways i couldn't make the cache work at all. i don't know what am i missing here..
这是我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的代码:
Also this is the code I'm using to get the 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
})
因此,在故障块中,我想加载缓存的数据,但是我不知道我缺少什么? 请提供有效的代码,缓存是一个大话题,我找不到完整的示例!
So in the failure block I'm suppose to load the cached data but i don't know what am i missing ? Please provide working code,caching is a big topic and i couldn't find a fully working sample!
推荐答案
伙计,我不太了解快速,但只要我知道您必须要做的就是:
Man, i don't know swift so well but as long as i know you will have to do is:
首先,从您的获取中捕获返回的数据,然后保存到NSCachedURLResponse中.在Objective-C中将是这样:
first of all, capture the returned data from your get and save then into NSCachedURLResponse. in objective-c will be something like that:
NSCachedURLResponse *cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:operation.response data:operation.responseData];
[[NSURLCache sharedURLCache] storeCachedResponse:cachedResponse forRequest:urlRequest];
此后,如果您的申请引发错误,您将恢复为该URL保存的先前数据.
After that, if your requisition throws error, you will recuperate you previous data saved for that URL.
NSData *data = [[[NSURLCache sharedURLCache] cachedResponseForRequest:urlRequest] data];
希望对您有所帮助.
这篇关于使用AFNetworking加载离线缓存的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!