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

OnlineOfflinejsonデータの解析方法は同じでなければなりません。どちらも同じです。同じプロセスを使用して使用したい場合は、Unparsedデータを使用してファイルを書き込む必要がありますが、解析されたjsonを使用したい場合は、それを書きますとして..data.jsonDocuments Directoryjsonplist

次の方法を試すことができます

-(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 に答える