JSON API cache in Xcode

Asked

Viewed 82 times

0

I want to cache my Wordpress JSON API 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 to cache with Afnetworking and Nsurlcache but I don’t 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];
           }
  • Hi guy will help or criticize me. I know how to speak and read. But no one answered me in English so I went here. I also wanted to help this site because it doesn’t have as many questions as the normal site.

  • Okay, sorry for the misunderstanding. And Ricardo’s answer, did not help? . . . Unfortunately iOS is not my area, if it were cache in WP could be. Good luck! . . . . PS: I deleted my previous comment, which mentioned the duplicate post on the website in English.

1 answer

2

Ideally, you should cache this information in a local database (Sqlite or Coredata) and check whether the user has a connection. By own Afnetworking has a class for this:

- (void)viewDidLoad {
    [super viewDidLoad];

    [[AFNetworkReachabilityManager sharedManager] startMonitoring];

}

- (BOOL)connected {
    return [AFNetworkReachabilityManager sharedManager].reachable;
}   

Browser other questions tagged

You are not signed in. Login or sign up in order to post.