views:

124

answers:

3

Hello,

I am interested in building a Timer Based game such as mafia wars or soemthing like that. I'm stuck on one question.

What would be the best way to retain a timer, even if the app is closed?

Should I do this based on the Device Clock? or should I set a time to a server, and get the time when the device starts up?

If any one knows a better way for this,

let me know. Thanks.

@lessfame

A: 

If you only need to retain the time and show how much time elapsed since the game was closed (i.e. you don't need to notify the user when the time is up), you can use the [NSDate timeIntervalSinceNow] method to determine the amount of milliseconds that passed between two times.

Senseful
CFAbsoluteTimeGetCurrent is UTC (with handwavey leapseconds), not local time.
tc.
@tc.: fixed it, good catch.
Senseful
A: 

If you are saying you want to just know time elapsed since some event, all you do is log the initial time, and then log the final time and compare the difference.

If you need a countdown timer to some event then what you do is set up a local push notification set to go off at the end time.

jamone
A: 

I'll interpret your question as "What's the best way to measure elapsed time between app launches?" instead of "How do I make a timer fire when my app is closed?".

There's no reliable and accurate way to measure time when the device is powered off (remote servers might not be reachable, astronomical measurements might not be possible if it's cloudy, ...). Don't bother.

That said, most CF/NS APIs use CFAbsoluteTime/NSDate (namely, CFRunLoopTimerGetNextFireDate() and -[NSTimer fireDate]). I'm not sure what they do if the system clock changes.

You can use mach_absolute_time() (and it's used internally by some things), but that's just system uptime, so it fails if the phone reboots. I'm not sure if you can get the boot UUID in order to find out if the phone has rebooted.

At the end of the day, CFAbsoluteTimeGetCurrent() or (equivalently) [NSDate date] is probably enough; just make sure that your app behaves sensibly if the time suddenly changes by a day or two in either direction.

Yes, the user can game the system by setting the system clock. You can mitigate this to some extent by occasionally syncing with the server, and keeping track of game time elapsed between syncs. If the difference between elapsed game time and server time is small, then just speed up or slow down the game appropriately to bring elapsed "game time" to real time. If the change is large, you can restore from the last save point on the server, or make the user wait until the elapsed game time has elapsed in server time, or a bunch of other things. This means you can't start playing until the initial sync, but the user has to be online to download the app anyway, so it's not a major problem.

tc.