ios - 使用 AFNetworking 加载离线缓存的 JSON

标签 ios objective-c swift afnetworking-2

我一直在尝试使用 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/

相关文章:

ios - Xcode : Add attachment using picker to email

iphone - 制作一个改变iPhone跳板背景的应用程序

objective-c - @try @catch 不起作用

ios - 根据用户在 swift 中输入的数组创建键值对

ios - 为 CGPoint 和 CGVector 创建快速泛型

ios - iOS 7:从json响应中选择特定对象

ios - 可以在没有 DEP 的情况下强制 iOS 更新 OTA 吗?

ios - 点击通过 UISlider

ios - ARKit 中带有动画的 .fbx 文件

ios - iOS 通用应用程序链接是否可以支持使用同一域的多个应用程序?