首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在iOS中实现离线缓存阅文app?

如何在iOS中实现离线缓存阅文app?
EN

Stack Overflow用户
提问于 2014-09-08 15:28:30
回答 2查看 239关注 0票数 0

我正在构建一篇阅读and的文章,我正在从服务器获取JSON格式的数据,并将其加载到UITableView和UIWebView中。

一篇文章包含图像、视频和文本。我想做离线缓存手段,如果没有互联网用户可以阅读以前加载的文章。我已经使用了图像的异步线程。

下面是我的代码:

代码语言:javascript
复制
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self checkInternetConnection];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20,10,0,20)];
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.text = @"Story";
    [self.navigationItem setTitleView:titleLabel];

    UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    spinner.center = CGPointMake(160, 240);
    spinner.hidesWhenStopped = YES;
    [self.view addSubview:spinner];
    [spinner startAnimating];
    BOOL myBool = [self isNetworkAvailable];
    if (myBool)
    {
        @try {

            self.tableView.separatorColor = [UIColor colorWithRed:190/255.0 green:190/255.0 blue:190/255.0 alpha:1.0];

            // for displaying the previous screen lable with back button in details view controller        UIBarButtonItem *backbutton1 = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleBordered target:nil action:nil];
            [[self navigationItem] setBackBarButtonItem:backbutton1];
            _Title1 = [[NSMutableArray alloc] init];
            _Author1 = [[NSMutableArray alloc] init];
            _Images1 = [[NSMutableArray alloc] init];
            _Details1 = [[NSMutableArray alloc] init];
            _link1 = [[NSMutableArray alloc] init];
            _Date1 = [[NSMutableArray alloc] init];
            pageNumber=1;
            NSData* data = [NSData dataWithContentsOfURL:ysURL];
            NSArray *ys_avatars = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            if(ys_avatars){
                for (int j=0;j<ys_avatars.count;j++)
                {
                    [_Title1 addObject:ys_avatars[j][@"title"]];
                    [_Author1 addObject: ys_avatars[j][@"author"]];
                    [_Images1 addObject: ys_avatars[j][@"featured_img"]];
                    [_Details1 addObject:ys_avatars[j][@"content"]];
                    [_link1 addObject:ys_avatars[j][@"permalink"]];
                    NSString *newStr=[ys_avatars[j][@"date"] substringToIndex:[ys_avatars[j]        [@"date"] length]-3];
                    [_Date1 addObject:newStr];
                }
            }
            else
            {
                NSLog(@"asd");
            }
        }
        @catch (NSException *exception) {

        }
        dispatch_queue_t downloadQueue = dispatch_queue_create("downloader", NULL);
        dispatch_async(downloadQueue, ^{
            // do our long running process here
            [NSThread sleepForTimeInterval:3];
            // do any UI stuff on the main UI thread
            dispatch_async(dispatch_get_main_queue(), ^{
                [spinner stopAnimating];
            });
        });
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *Cellidentifier1 = @"ysTableViewCell";
    ysTableViewCell *cell1 = [tableView      dequeueReusableCellWithIdentifier:Cellidentifier1 forIndexPath:indexPath];
    long row = [indexPath row];
    cell1.TitleLabel1.text = _Title1[row];
    cell1.AuthorLabel1.text = _Author1[row];
    NSString *yourStoryUrl = [_Images1[indexPath.row]  stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
    if(yourStoryUrl) {
        NSArray *subStringsUrl = [yourStoryUrl componentsSeparatedByString:@"/"];
        NSString *stripedName = [subStringsUrl lastObject];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString* filePath =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",stripedName]];
        NSLog(@"File Path retrieved %@", filePath);
        if(filePath) {
            UIImage *image = [UIImage imageWithContentsOfFile:filePath];
            if(image) {
                ysTableViewCell  *updateCell =(id)[tableView cellForRowAtIndexPath:indexPath];
                if(updateCell)
                    updateCell.ThumbImage1.image=image;
                cell1.ThumbImage1.image=image;
            } else {
                dispatch_queue_t taskQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                dispatch_async(taskQ, ^{
                    NSURL *Imageurl = [NSURL URLWithString:yourStoryUrl];
                    NSData *data =  [NSData dataWithContentsOfURL:Imageurl];
                    UIImage *images1 = [[UIImage alloc] initWithData:data];
                    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                    NSString *documentsDirectory = [paths objectAtIndex:0];
                    NSData *imageData = UIImagePNGRepresentation(images1);
                    //_imagePath =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",stripedName]];
                    if (![imageData writeToFile:filePath atomically:NO])
                    {
                        NSLog((@"Failed to cache image data to disk"));
                    }
                    else
                    {
                        NSLog((@"the cachedImagedPath is %@",filePath));
                    }
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        ysTableViewCell  *updateCell =(id)[tableView cellForRowAtIndexPath:indexPath];
                        if(updateCell)
                            updateCell.ThumbImage1.image=images1;
                        cell1.ThumbImage1.image=images1;
                    });
                });
                return cell1;
            }
EN

回答 2

Stack Overflow用户

发布于 2014-09-08 17:22:41

对于离线存储,您已经创建了一个sqlite文件,将从JSON获得的所有详细信息存储到数据库中。在数据库中只存储图像和视频的文件路径。下载这些资源并将其存储在文档目录中。

谢谢。

票数 0
EN

Stack Overflow用户

发布于 2014-09-08 22:43:14

您可以使用键控归档(NSKeyedArchiver/NSKeyedUnarchiver)

这是一个tutorial

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25719286

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档