【问题标题】:How would I go about saving a JSON file from a webservice to a local JSON file?我将如何将 JSON 文件从 web 服务保存到本地 JSON 文件?
【发布时间】:2013-09-05 09:23:11
【问题描述】:

我目前正在使用来自远程 Web 服务的 JSON 数据(NSArray 格式)填充 UITableView。我想通过调用 web 服务并将 JSON 数据存储到本地文件来加速应用程序。

另外,这是一个好方法吗?这样用户就不必一直下载数据了?

我坚持的是如何将远程 JSON 文件保存到本地文件。在我的-(void)saveJsonWithData:(NSData *)data 方法中如何保存远程数据。

这是我目前使用的代码(来自一些 Stackoverflow 搜索)

-(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];
}

感谢帮助

【问题讨论】:

    标签: iphone ios objective-c json uitableview


    【解决方案1】:

    在 iOS 上,您应该使用 NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) 来获取文档目录。没有用户目录。

    【讨论】:

    • 谢谢!但是你知道我如何将 NSURL 中的 json 保存到本地 json 文件中吗?
    • 您的方法将保存数据。我假设您已经有一些其他代码可以进行下载。
    【解决方案2】:

    让iOS做JSON解析,然后通过输出流写入纯文本文件

    NSData *jsonData = yourData;
    NSError *error;
    
    // array of dictionary
    NSArray *array = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:&error];
    
    if (error) {
        NSLog(@"Error: %@", error.localizedDescription);
    } else {
        NSArray *documentsSearchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [documentsSearchPaths count] == 0 ? nil : [documentsSearchPaths objectAtIndex:0];
    
        NSString *fileName = @"file.json";
    
        NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
    
        NSOutputStream *outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:YES];
        [outputStream open];
    
        [NSJSONSerialization writeJSONObject:array
                                    toStream:outputStream
                                     options:kNilOptions
                                       error:&error];
        [outputStream close];
    }
    

    【讨论】:

      猜你喜欢
      • 2016-03-13
      • 2018-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      • 2019-07-23
      相关资源
      最近更新 更多