JSON API cache in Xcode

0

I want to cache the JSON API from my Wordpress in my app. I want a cache of tableview cells and UIWebView for when in airplane mode or off or with bad signal, the user can still see. I tried caching with AFNetworking and NSURLCache but I do not know how. How can I format AFNetworking or NSURLCache for this?

 NSURL *blogURL =[NSURL    URLWithString:@"http://purpledrop.org/api/get_recent_summary/"];

 NSURLSession *session = [NSURLSession sharedSession];

 NSURLSessionDownloadTask *task = [session downloadTaskWithURL:blogURL  completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {

NSData *jsonData = [[NSData alloc] initWithContentsOfURL:location];
//this app would crash without this code below in airplane mode or no wifi
if (jsonData ==nil) {
    return;
}

NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];

self.blogPosts = [NSMutableArray array];

NSArray *blogPostArray = [dataDictionary objectForKey:@"posts"];

for (NSDictionary *bpDictionary in  blogPostArray) {
    BlogPost *blogPost = [BlogPost blogPostWithTitle:[bpDictionary objectForKey:@"title"]];
    blogPost.author = [bpDictionary objectForKey:@"author"];
    blogPost.thumbnail = [bpDictionary objectForKey:@"thumbnail"];
    blogPost.date = [bpDictionary objectForKey:@"date"];
    blogPost.url = [NSURL URLWithString:[bpDictionary objectForKey:@"url"]];
    [self.blogPosts addObject:blogPost]; 
      }  
dispatch_async(dispatch_get_main_queue(), ^{
      [self.tableView reloadData];    
                      });  
               }];
             [task resume];
           }
    
asked by anonymous 02.08.2014 / 03:44

1 answer

2

Ideally, you should cache this information in a local database (SQLite or CoreData) and check if the user has a connection. By itself AFNetworking has a class for this:

- (void)viewDidLoad {
    [super viewDidLoad];

    [[AFNetworkReachabilityManager sharedManager] startMonitoring];

}

- (BOOL)connected {
    return [AFNetworkReachabilityManager sharedManager].reachable;
}   
    
07.08.2014 / 14:40