简体   繁体   中英

Implementing persistent countdown timer

There are some games where certain actions are time related. For example, every 24 hours user gets one credit if he played a game ... After we turn off our phone and come back after few hours timer is correctly set.

How is this done ? There must be some method which writes current time into a persistent storage and then reads from it?

I am just guessing it's something like this:

 NSDate * now = [NSDate date];
 NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
 [outputFormatter setDateFormat:@"HH:mm:ss"];
 NSString *newDateString = [outputFormatter stringFromDate:now];

And then comes part where newDateString is written into persistent storage.

Also, if this is a method, what happens if user change time manually on his device? Can we rely on this or there are some other methods to track real time passed between certain moments in the game?

You could do this by writing the next award time to NSUserDefaults and comparing previous values.

// Fetch previous "next award" time.
NSNumber *previousTime = [[NSUserDefaults standardUserDefaults] objectForKey:@"next_award_time"];
NSTimeInterval now = [[NSDate date] timeIntervalSince1970];

// If we haven't yet scheduled a "next award" time, or if we've passed it..
if (!previousTime || [previousTime doubleValue] < now) {
  // We had a previous value, so we've passed the time.
  if (previousTime) {
    // Award user.
  }
  // Set next award time.
  NSTimeInterval nextTime = [[NSDate date] timeIntervalSince1970] + 60*60*24;
  [[NSUserDefaults standardUserDefaults] setObject:@(nextTime) forKey:@"next_award_time"];
}

As far as worrying about users changing their own device time, you'll need to make a network request to an unbiased third-party clock. This could be a server you control or a well-known time server. You might want to check out this answer for help on how to contact an NTP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM