I am trying to design a system where real-time events happen and I want to synchronise them to a clock. [NSDate date]
would normally be ok but the user could change this and cheat the system. All I need is a clock that I can take relative times from (a 64-bit counter for example) - I don't need absolute time (or time of day etc).
Is there such an API I can use?
EDIT: I would also like to add that this clock needs to be persistent over sessions of the application.
Make sure that you have the latest version of iOS or iPadOS. Turn on Set Automatically1 in Settings > General > Date & Time. This automatically sets your date and time based on your time zone. If a message appears saying that updated time zone information is available, restart your device and any paired Apple Watch.
On your iPhone, iPad or iPod touchTurn on Set Automatically1 in Settings > General > Date & Time. This will set your date and time automatically based on your time zone.
The best monotonically increasing number on an iPhone is mach_absolute_time()
which is a count of CPU ticks since the last reboot. If you would like it in seconds for any reason, it is most easily fetched with CACurrentMediaTime()
.
Using this to create an "always-increment" is pretty easy. On first launch, store the current value wherever you like. When you exit, and periodically, save the offset from that value. When you restart, check the current value; if it is less than your previous base value, replace your base value (there's been a reboot).
All of this of course can be cleared by removing your app unless you store something on the server.
Note that this cannot be used as a strong security measure. There is no way to prevent an authorized user from forging requests. So depending on what you mean by "cheat the system," it may not be a solvable problem. The best you can do is have constant diligence looking for hacks and dealing with them.
If all you need is a clock to measure events as monotonically increasing, you could just get the current system uptime ala clock_gettime(CLOCK_MONOTONIC)
. If restarting the device is a problem, just save the last value used and at next launch use the last saved value as an offset. The Problem here may be that if they actually shut the device off, it won't count that time. But if you're worried about the user speeding up time, they can't do that, only slow it down.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With