【发布时间】:2014-07-03 04:37:27
【问题描述】:
我正在开发一个通过 json 从网络下载数据的应用程序。正如我在教程和帖子中看到的那样,我将缓存策略设置为使用缓存。好吧,当应用程序启动时,它会下载一次数据,如果我关闭视图并在飞行模式下重新打开它,数据将从缓存中加载。但是如果我关闭应用程序然后重新启动它,不要从缓存加载并再次请求服务器(或者如果飞行模式打开则显示错误)。我需要在磁盘上缓存数据以供离线使用...请帮助
这是我的代码:
AppDelegate.m
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:5 * 1024 * 1024
diskCapacity:100 * 1024 * 1024
diskPath:@"nsurlcache"];
[NSURLCache setSharedURLCache:sharedCache];
和请求:
NSString *string = @"http://********.es/api/get_posts/?post_type=listing";
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCacheResponseBlock:^NSCachedURLResponse *(NSURLConnection *connection, NSCachedURLResponse *cachedResponse) {
NSCachedURLResponse * newCachedResponse = [[NSCachedURLResponse alloc]
initWithResponse:cachedResponse.response
data:cachedResponse.data
userInfo:cachedResponse.userInfo
storagePolicy:NSURLCacheStorageAllowed];
return newCachedResponse;
}];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
_lista = responseObject[@"posts"];
[self.tableView reloadData];
//NSLog(@"%@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Data"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alertView show];
}];
[operation start];
我在网上尝试了很多解决方案,但没有人能按我的意愿工作,所以我认为问题出在我的代码中......
【问题讨论】:
标签: ios json caching afnetworking