質問

I am developing an app that download data from the web through json. I set the cache policy to use the cache as I have seen in tutorials and posts. Well, when the app starts, it downloads the data once and if I close the view and reopen it in flight mode, the data is loaded from cached. But if I close the app and then restart it, do not load from cache and request the server again (or show error if flight mode is on). I need caching data on disk for offline usage... help please

here is my code:

AppDelegate.m

NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:5 * 1024 * 1024
                                                        diskCapacity:100 * 1024 * 1024
                                                            diskPath:@"nsurlcache"];
[NSURLCache setSharedURLCache:sharedCache];

and the request:

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

I have tried a lot of solutions on the web and no one works as I would like, so I think the problem is something wrong in my code...

役に立ちましたか?

解決

I think the functionality you are wanting here is going to require using core data or writing your own caching using NSFileManager. Figure out the best approach for your app. There is a pretty cool article about NSFileManager by Mattt Thompson here

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top