我有一个 Web 服务来获取JSON
表单中的数据。appDidFinishLaunching
每次应用程序启动(内部方法)并将其存储在本地文件中时,我都会调用此服务。我只想在第一次启动应用程序时调用该服务,并且从下一次我只想使用我存储JSON
数据的文件。
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//live json data url
NSURL *url = [NSURL URLWithString:@"My Url"];
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];
}
NSError *jsonError = nil;
NSString *jsonFilePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"data.json"];
NSData *jsonData = [NSData dataWithContentsOfFile:jsonFilePath options:kNilOptions error:&jsonError ];
NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&jsonError];
self.serverResponseArray = jsonArray;
NSLog(@"%@",self.serverResponseArray);
通过这段代码,我正在编写JSON
对本地文件的响应并将其存储在一个数组中以在整个应用程序中使用它。