Peter
Peter

Reputation: 549

Implementing a persistent clock

I'm currently working on a new game for iOS using Cocos2D. The game needs to advance states after x amount of time since the first launch. So for example:

State - Time

  1. initial launch
  2. 24hrs
  3. 48hrs

My first idea was to just get the data and time on first launch and save it to a file. Then I could check it ever now and again to see how much time has passed. The problem with this is I need it to be in realtime so that the changes will take effect immediately once the state is reached. It also needs to continue when the user is not using the app. The functionality I'm looking for is kind of similar to how the iOS strategy games work where you build structures that take x amount of time.

Anyway my question(s) is; is there some sort of library that can accomplish this and how can I get it to continue after the user exits the app?

Upvotes: 0

Views: 92

Answers (1)

TheEye
TheEye

Reputation: 9346

It can't. There is - apart from kind of misusing video/music playing etc. no way for your app to do work while it is not running.

You have two things you can do to simulate that behavior (and I suppose the strategy games do this, too):

  1. You can calculate at any time while a user is still running your app the points in the future when something should happen (eg a housing structure is finished). When the user leave your app, store these future times as local events - then the user will get notified that something has happened in your game (eg message "The church has been built. Do you want to go to church now?)". Pressing yes will open your app, and you can do whatever is necessary to indeed build the church. So in fact you don't do it at the time when it occurred, but when the user opens your app the next time.
  2. Like 1, but without notification. Just remember when the user leaves the app (eg in your settings, I would use a property list; set it when the app delegate gets the appWillResignActive event), and the next time he starts do whatever would have been done in the meantime - he won't be able to tell the difference :-).

It's all about make believe here :-).

Upvotes: 3

Related Questions