I am currently coding an app which calls a text file from a store, displays it and then increments so that the next file can be loaded when needed. I have got the base code to work by the use of a button click however I want it to be able to call the text file only when 24 hours has past since the last one was loaded effectively making it update every day.
I am trying to do this by using NSDate and NSUserDefaults to store the previous time that a file was called and then compare it to the current time, if it has been more than 24 hours increment and call the next.
However after trying to add things and change around the base code below I just cannot work out how to get it to work. I don’t know if this is just because I have not had enough experience and don’t know the language well enough or if I am just being a bit silly and missing something really simple.
Any help would be greatly appreciated.
NSDate *nowDate = [NSDate date];
[[NSUserDefaults standardUserDefaults] setObject:nowDate forKey:@"LastLoaded"];
NSDate *lastLoaded = [[NSUserDefaults standardUserDefaults] objectForKey:@"LastLoaded"];
NSDate *checkDate = [NSDate dateWithTimeIntervalSinceNow:-24*60*60];
if([lastLoaded compare:checkDate] == NSOrderedAscending) {
static int number = 1;
NSString *filePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%i",number++] ofType:@"txt"];
if (filePath) {
NSString *textFromFile = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
if (textFromFile) {
textView.text = textFromFile;
}
}
}
There is a bug in your code. You are not retrieving the last update date from NSUserDefaults. You are retrieving the current date, as you are overwriting the LastUpdatedate with current date in the very second line of code.