我如何实现JSON的离线缓存?

时间:2014-09-26 15:07:31

标签: ios objective-c json afnetworking offline-caching

我正在构建一个像TechCrunch这样的文章阅读应用程序。我从服务器获取JSON内容的数据,并在UITableView中显示JSON内容,如文章图像,标题和作者名称。

当用户点击它在UIWebView中打开的文章时。

我已经通过我已经在UITableView中获取的segue传递了文章的标题,作者姓名和内容。

我在我的项目中集成了第三方库,即AFNetworking。我想实现文章的离线缓存意味着如果没有互联网用户可以阅读文章。

这是我的代码:

TableView.m

              - (void)viewDidLoad
             {
                [super viewDidLoad];
                tempJson = [[NSMutableArray alloc] init];
                [self.tableView reloadData];
                NSString *jsonLink=[NSString stringWithFormat:@“www.example.com&page=1"];
                NSURL *url = [[NSURL alloc] initWithString:jsonLink];
                NSURLRequest *request = [NSURLRequest requestWithURL:url];
                AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
                operation.responseSerializer = [AFJSONResponseSerializer serializer];
                [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
                 NSArray *jsonArray = (NSArray *)responseObject;
                 for (NSDictionary *dic in jsonArray) {
                Json *json = [[Json alloc] initWithDictionary:dic];
                [tempJson addObject:json];
                   }
                self.jsons = [[NSArray alloc] initWithArray:tempJson];
                [self.tableView reloadData];
               } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error"
                                             message:[error localizedDescription]
                                                   delegate:nil
                                                   cancelButtonTitle:@"Ok"
                                                   otherButtonTitles:nil];
                                                   [alertView show];

                                             }];
                                           [operation start];
                               [self.tableView addInfiniteScrollingWithActionHandler:^{
                                   }];
                                 }

                -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
                  {
                     if ([[segue identifier] isEqualToString:@"ShowDetails1"]) {
                     Webview *ysdetailviewcontroller = [segue destinationViewController];
                     NSIndexPath *myindexpath1 = [self.tableView indexPathForSelectedRow];
                     long row1 = [myindexpath1 row];
           dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                     ysdetailviewcontroller.DetailModal1 = @[[self.jsons[row1] title],          [self.jsons[row1] author],[self.jsons[row1] a_image],[self.jsons[row1] content], [self.jsons[row1] link],[self.jsons[row1] date]];
                         });
                       } 
                      }

Webview.m

                - (void)viewDidLoad
                     {
                  [super viewDidLoad];
                  NSString *Title=[NSString stringWithFormat:@"<div style=\"line-height:80px;font-size:70px;font-family: Helvetica, Arial, Sans-Serif;font-weight:600;padding-left:40px; !important;padding-right:40px; !important;\">%@</div>",  _DetailModal1[0]];
                  NSString *AuthorName=[NSString stringWithFormat:@"<div><div style=\"color:#9E9E9E;line-height:70px;font-size:35px;font-family: Helvetica, Arial, Sans-Serif;font-weight:800;float:left;float:left;text-align:left;padding-left:40px; !important;\">%@&nbsp&nbsp</div>",_DetailModal1[1]];
                  NSString *Date=[NSString stringWithFormat:@"<div style=\"line-height:70px;font-size:35px;font-family: Helvetica, Arial, Sans-Serif;font-weight:200;\">%@</div></div><br><br>",_DetailModal1[5]];
                  NSString *url=[[NSString alloc] initWithString:_DetailModal1[3] ];//_DetailModal1[3] contains article content
                  NSString *javaScriptStar=@"<!DOCTYPE html><html><head><body></head><div style = \"line-height:70px !important;font-size:52px !important;font-family: Helvetica, Arial, Sans-Serif;font-weight:400;padding-left:40px; !important;padding-right:40px; !important;\">";
                  NSString *javaScriptEnd=@"</font></div></body></html>";
                  NSString *javaScriptLink=@"<body link=\"#3366CC\”>";  
                  NSString *javaScriptDec=@"<style type=\"text/css\">a {text-decoration: none; font-weight:bold; }img {  display: block;margin-left: auto; margin-right: auto;margin-top: 8px;margin-bottom: 8px; width : 800px !important;height:auto;}</style>";
                  NSString* myURLString = [NSString stringWithFormat:@"%@%@%@%@%@%@%@%@",Title,AuthorName,Date, javaScriptDec, javaScriptLink,javaScriptStar,url,javaScriptEnd];
                  NSString *htmlString = [myURLString  stringByReplacingOccurrencesOfString:@"src=\"//" withString:@"src=\"https://"];
                 _webView.delegate = self;
                 [_webView loadHTMLString:htmlString baseURL:nil];
                  }

2 个答案:

答案 0 :(得分:1)

有很多方法可以将数据保存到磁盘:例如,您可以使用Core Data或原始SQLite。对于这么简单的事情,最简单的方法就是将JSON字符串写入文件,并在想要显示文章时将其读回。看一下Apple的File System Programming Guide

答案 1 :(得分:1)

您可能需要查看NSURLCache。由于AFNetworking建立在NSURLConnection之上,因此在app delegate中设置缓存应该完全按照您的要求进行操作。