AFNetworking AFJSONRequestOperation缓存& API请求限制

时间:2014-04-23 20:30:36

标签: ios afnetworking

我使用下面的代码从api中提取数据。我想利用缓存或其他东西仅每3小时请求一次信息。这是我最好的选择吗?

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

    success([NSMutableArray arrayWithArray:[[JSON objectForKey:@"daily"] objectForKey:@"data"]]);

} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON){

    failure(error);

}];

1 个答案:

答案 0 :(得分:0)

我认为最好的方法(如果可以)是在响应请求上设置max-age标头,让NSURLCache处理所有逻辑。

在此处查看如何设置max-age和其他标头:http://www.mnot.net/cache_docs/#CACHE-CONTROL

要在您的应用上启用缓存,只需将其放在app delegate didFinishLoading上:

//Here we declare a shared NSURLCache with 2mb of memory and 100mb of disk space
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:2 * 1024 * 1024
                                          diskCapacity:100 * 1024 * 1024
                                          diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];