我有一个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
响应本地文件并存储在一个数组中,以便在整个应用程序中使用它。
答案 0 :(得分:2)
static NSString * const someKey = @"haveChecked";
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSUserDefaults * stdUserDefaults = [NSUserDefaults standardUserDefaults];
if(![[stdUserDefaults objectForKey:someKey] boolValue])
{
[self trySomething];
}
}
-(void)gotJson
{
//async callback
NSUserDefaults * stdUserDefaults = [NSUserDefaults standardUserDefaults];
[stdUserDefaults setBool:YES forKey:someKey];
[stdUserDefaults synchronize];
}
听起来你需要学习处理文件,所以这里有一些堆栈溢出读取:
What is the documents directory (NSDocumentDirectory)?
Write a file on iOS
答案 1 :(得分:0)
试试这个
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if ([self fetchFromNSUserDefaults:@"FirstTimeNO"]==nil || [FunctionManager fetchFromNSUserDefaults:@"FirstTimeNO"]==@"") {
[self YourFunctionThatCallFirstTime];
}
return YES;
}
-(id)fetchFromNSUserDefaults:(NSString *)strKey{
NSUserDefaults *objUserDefaults = [NSUserDefaults standardUserDefaults];
return [objUserDefaults objectForKey:strKey];
}
-(void)addToNSUserDefaults:(id)objValue forKey:(NSString *)strKey{
NSUserDefaults *objUserDefaults = [NSUserDefaults standardUserDefaults];
[objUserDefaults setObject:objValue forKey:strKey];
[objUserDefaults synchronize];
}
-(void)YourFunctionThatCallFirstTime {
//Your Stuff
[self addToNSUserDefaults:@"1" forKey:@"FirstTimeNO"];
}