我收到了JSON响应,并且当前能够使用我的应用程序中的数据.
我想将此响应保存到文件中,以便我可以在项目中的JS文件中引用.我已经在应用程序启动时请求了一次这样的数据,所以为什么不将它保存到文件中并引用它,因此只需要对数据进行一次调用.
我的UIWebView的HTML文件使用"创建文件夹引用"选项导入到我的Xcode项目中,我的JS文件的路径是 html->js->app.js
我想将响应保存在data.json设备上的某个位置,然后像我这样在我的js文件中引用request.open('GET', 'file-path-to-saved-json.data-file', false);
我怎样才能做到这一点?
在完成这个想法之后,我想出了更多内容.
安装应用程序时,包中的默认数据文件将复制到Documents文件夹.当应用程序didFinishLaunchingWithOptions运行时,我调用以下方法:
- (void)writeJsonToFile
{
//applications Documents dirctory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//live json data url
NSString *stringURL = @"http://path-to-live-file.json";
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];
}
}
Run Code Online (Sandbox Code Playgroud)
然后在整个应用程序中,当我需要引用数据时,我使用保存的文件.
//application Documents dirctory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSError *jsonError = nil;
NSString *jsonFilePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"data.json"];
NSData *jsonData = [NSData dataWithContentsOfFile:jsonFilePath options:kNilOptions error:&jsonError ];
Run Code Online (Sandbox Code Playgroud)
为了在我的JS代码中引用json文件,我为"src"添加了一个URL参数,并将文件路径传递给Applications Documents文件夹.
request.open('GET', src, false);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13328 次 |
| 最近记录: |