我一直在尝试使用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
})
所以在故障块中我想加载缓存的数据,但我不知道我错过了什么? 请提供工作代码,缓存是一个很大的主题,我找不到一个完整的工作样本!
答案 0 :(得分:1)
伙计,我不太了解,但只要我知道你必须做的就是:
首先,从获取中捕获返回的数据,然后保存到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];
我希望能帮助你。