【问题标题】:NSURLRequest not caching on disk using AFNetworkingNSURLRequest 不使用 AFNetworking 缓存在磁盘上
【发布时间】: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


    【解决方案1】:

    我认为您在这里想要的功能将需要使用核心数据或使用 NSFileManager 编写您自己的缓存。找出最适合您的应用的方法。 Mattt Thompson here 有一篇关于 NSFileManager 的非常酷的文章

    【讨论】:

    • 所以ios系统缓存不起作用?我找不到明确的答案来选择要遵循的路径
    • 非常感谢,最后,我尝试了这个例子并且工作正常
    猜你喜欢
    • 2015-12-02
    • 2023-04-07
    • 2016-07-16
    • 2011-01-22
    • 2011-03-04
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多