1

我想在我的应用程序中使用 json。我可以使用以下代码从 url 解析 json:

#import "ViewController.h"
@implementation ViewController
{
    NSDictionary *titles;
    NSMutableData *Data;
    NSArray *fileContent;
    NSArray *folderContent;
    NSMutableArray *all;
}
@synthesize Table;
- (void)viewDidLoad
{
    [super viewDidLoad];  
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    NSURL *url =[NSURL URLWithString:@"http://192.168.1.100/veis/root/developers/api/filemanager.php?key=5147379269&getlist=root"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [[NSURLConnection alloc]initWithRequest:request delegate:self];

}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    Data = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
    [Data appendData:theData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

    titles = [NSJSONSerialization JSONObjectWithData:Data options:kNilOptions error:nil];
    fileContent = [titles objectForKey:@"fileContent"];
    folderContent = [titles objectForKey:@"folderContent"];
    all = [[NSMutableArray alloc]init];
    [all addObjectsFromArray:folderContent];
    [all addObjectsFromArray:fileContent];
    [Table reloadData];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    UIAlertView *errorView = [[UIAlertView alloc]initWithTitle:@"Error" message:@"The Connection has been LOST" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [errorView show];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

但是我想当我没有互联网时可以使用 json。我不知道如何以离线方式(或我的设备本地)使用 json

你能在这个问题上指导我如何离线使用 json

4

1 回答 1

6

Online和json数据的解析方式应该是一样的Offline,都是一样的,只是你需要用Unparsed数据写一个文件说data.jsonin Documents Directory,如果你想使用相同的进程来使用json,但是如果你想使用解析的json,那就写吧作为plist..

您可以尝试使用以下方法

-(void)saveJsonWithData:(NSData *)data{

     NSString *jsonPath=[[NSSearchPathForDirectoriesInDomains(NSUserDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingFormat:@"/data.json"];

     [data writeToFile:jsonPath atomically:YES];

}

-(NSData *)getSavedJsonData{
    NSString *jsonPath=[[NSSearchPathForDirectoriesInDomains(NSUserDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingFormat:@"/data.json"];

    return [NSData dataWithContentsOfFile:jsonPath]
}

然后调用函数为

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

    [self saveJsonWithData:data];
}
于 2013-04-22T07:20:49.747 回答