将JSON文件保存到iPhone

时间:2013-12-12 12:11:22

标签: ios iphone json

我希望每次从服务器保存json文件,当用户有互联网连接使用它时,iPhone没有互联网连接。但它不起作用。这是我的代码:

- (void)writeJsonToFile
{
    //applications Documents dirctory path
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    //live json data url
    NSString *stringURL = @"http://volodko.info/ic/json.php";
    NSURL *url = [NSURL URLWithString:stringURL];
    NSData *urlData = [NSData dataWithContentsOfURL:url];

    //attempt to download live data
    if (urlData)
    {
        NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"data.json"];
        [urlData writeToFile:filePath atomically:YES];
    }
    //copy data from initial package into the applications Documents folder
    else
    {
        //file to write to
        NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"data.json"];

        //file to copy from
        NSString *json = [ [NSBundle mainBundle] pathForResource:@"data" ofType:@"json" inDirectory:@"html/data" ];
        NSData *jsonData = [NSData dataWithContentsOfFile:json options:kNilOptions error:nil];

        //write file to device
        [jsonData writeToFile:filePath atomically:YES];
    }
}

6 个答案:

答案 0 :(得分:2)

试试这个。 。 。

- (void)writeJsonToFile
{
    //applications Documents dirctory path
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    //live json data url
    NSString *stringURL = @"http://volodko.info/ic/json.php";
    NSURL *url = [NSURL URLWithString:stringURL];
    NSData *urlData = [NSData dataWithContentsOfURL:url];

    //attempt to download live data
    if (urlData)
    {
        NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"data.json"];
        [urlData writeToFile:filePath atomically:YES];
    }
    //copy data from initial package into the applications Documents folder
    else
    {
        //file to write to
        NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"data.json"];;

        //file to copy from
        NSString *json = [ [NSBundle mainBundle] pathForResource:@"data" ofType:@"json" inDirectory:@"html/data" ];
        NSData *jsonData = [NSData dataWithContentsOfFile:json options:kNilOptions error:nil];

        //write file to device
        [jsonData writeToFile:filePath atomically:YES];
    }
}

答案 1 :(得分:2)

这对我有用。阅读AFJSONRequestOperation指南。该代码还检查json文件是否已经被缓存。

NSString *path = @"http://volodko.info/ic/json.php";
    NSURL *url = [[NSURL alloc] initWithString:path];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

    id cachedJson = [[NSUserDefaults standardUserDefaults] valueForKey:path];
    if (cachedJson) {
        [self didUpdateJSON:cachedJson];
    } else {
        AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
            [self didUpdateJSON:JSON];
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSUserDefaults standardUserDefaults] setObject:JSON forKey:path];
                [[NSUserDefaults standardUserDefaults] synchronize];
            });
        } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
            NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
        }];
        [operation start];
    }

答案 2 :(得分:2)

从JSON解析器获取数据并将其存储在数组中。之后,您可以将其添加到SQLite数据库中。

答案 3 :(得分:0)

你应该以适当的方式创建路径

替换此

NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"data.json"];

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"data.json"];

答案 4 :(得分:0)

尝试使用NSUserDefaults而不是将此小JSON文本写入文件

- (void)writeJsonToFile
{
    NSString *jsonString;

    NSString *stringURL = @"http://volodko.info/ic/json.php";
    NSURL *url = [NSURL URLWithString:stringURL];
    NSData *urlData = [NSData dataWithContentsOfURL:url];

    if (urlData)
    {
        // JSON successfully downloaded, store it to user defaults
        jsonString = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
        [[NSUserDefaults standardUserDefaults] setValue:jsonString forKey:@"jsonString"];
    }
    else
    {
        // no urlData, using stored JSON
        jsonString = [[NSUserDefaults standardUserDefaults] valueForKey:@"jsonString"];
    }
}

可能更好:

- (NSString *)getJSON
{
    <the code above>
    return jsonString;
}

然后在其他函数中使用它:

NSString *jsonString = [self getJSON];

答案 5 :(得分:0)

Anton,获取json数据,并在您第一次运行数组时保存数据nsmutable array当您再次运行时,数组不是零,但第二次重播数据。另一种将数据存储在local database中的方法......如果你需要存储数据..

但是你的问题首先解决了......祝你好运..