我有一個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
響應本地文件,並在陣列中存儲在整個應用程序來使用它。
你可以只在嘗試加載數據之前測試文件的存在否? – talnicolas 2013-05-08 20:58:00
我該如何檢查。 ? – Zac24 2013-05-08 20:58:49
您第一次加載json,並將其存儲在具有特定名稱的本地文件中(如果我理解的很好)。下次啓動應用程序時,如果具有該名稱的文件存在,則不需要加載json,只需使用該文件即可。但出於好奇,你不希望每次啓動應用程序時都要更新這些數據嗎? – talnicolas 2013-05-08 21:01:05