如何将JSON文件从Web服务保存到本地JSON文件? [英] How would I go about saving a JSON file from a webservice to a local JSON file?
问题描述
我目前正在使用来自远程Web服务的JSON数据(NSArray格式)填充UITableView.我想通过调用Web服务并将JSON数据存储到本地文件来加速应用程序.
I'm currently populating a UITableView with JSON data (NSArray format) from a remote webservice. I would like to speed up the application by making a call to the webservice and storing the JSON data to a local file.
还有,这是一个好方法吗,这样用户不必一直保持下载数据的状态?
also, is this a good way to do this so the user doesn't have to keep downloading data all the time?
我遇到的问题是如何将远程JSON文件保存到本地文件.在我的-(void)saveJsonWithData:(NSData *)data
方法中,如何保存远程数据.
What I'm stuck on is how to save the remote JSON file to a local file. In my -(void)saveJsonWithData:(NSData *)data
method how do I save the remote data.
这是到目前为止我正在使用的代码(来自某些Stackoverflow搜索)
Here's the code I'm using so far (from some Stackoverflow searching)
-(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];
}
感谢帮助
推荐答案
在iOS上,您应该使用 NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)
来获取文档目录.没有用户目录.
On iOS you should be using NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
to get the document directory. There is no user directory.
这篇关于如何将JSON文件从Web服务保存到本地JSON文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!