Load offline cached JSON using AFNetworking

折月煮酒 提交于 2019-12-01 12:53:19

问题


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..

Here is the code in my 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
}

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!


回答1:


Man, i don't know swift so well but as long as i know you will have to do is:

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];

After that, if your requisition throws error, you will recuperate you previous data saved for that URL.

NSData *data = [[[NSURLCache sharedURLCache] cachedResponseForRequest:urlRequest] data];

I hope that helps you.



来源:https://stackoverflow.com/questions/31572050/load-offline-cached-json-using-afnetworking

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!