简体   繁体   English

实施持续倒数计时器

[英]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. 例如,如果用户玩过游戏,每24小时就会获得一个积分。...关闭手机电源,数小时后正确设置计时器后再回来。

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. 然后是将newDateString写入持久性存储的部分。

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. 您可以通过将下一个奖励时间写入NSUserDefaults并比较以前的值来实现。

// 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. 您可能想查看此答案以获取有关如何联系NTP的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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