How can I get the real time in iPhone, not the time set by user in Settings?

时光毁灭记忆、已成空白 提交于 2019-11-29 02:28:35

Get the time from NIST with the Daytime Protocol:

UDP Based Daytime Service A server listens for UDP datagrams on UDP port 13. When a datagram is received, an answering datagram is sent containing the current date and time as a ASCII character string (the data in the received datagram is ignored).

NIST Format of response: JJJJJ YR-MO-DA HH:MM:SS TT L H msADV UTC(NIST) OTM

http://tf.nist.gov/service/its.htm

http://tf.nist.gov/tf-cgi/servers.cgi

Maxm007

The best solution I've come up with is using the mach timer which counts time units since last iphone boot.

This works great. The only restriction is that the user cannot be allowed to reboot or it would invalidate his time.

I detect a reboot by initially storing the iphone timestamp associated with the mach timer and then checking every time the app starts, so it hasn't changed. This has as a side effect that if the user changes iPhone DateTime while he's being timed , that will also invalidate the score, but that is ok.

How can I detect whether the iphone has been rebooted since last time app started

I can easily warn my users about this: rebooting or changing iphone time while you're on the clock will invalidate your scored time.

JohnK

I just posted the following here:

This works to get the GPS time:

#import <CoreLocation/CoreLocation.h>

CLLocation* gps = [[CLLocation alloc]
                       initWithLatitude:(CLLocationDegrees) 0.0
                       longitude:(CLLocationDegrees) 0.0];
NSDate* now = gps.timestamp;

It doesn't seem to be tamper-proof though.

I tried this code on an iPhone 4 in airplane mode (iOS 6.1), and even then it gives a time all right. But unfortunately this time seems to change with the system clock. Ugh.

Funny thing that I found (still in airplane mode) is that if you tamper with the system clock (after turning to off Time & Date's Set Automatically), and then turn Set Automatically back to on, the machine restores the real (original) time without a hitch. this works even after cycling the phone's power. So it seems that there is something like a tamper-proof time the device maintains internally. But how to access this?

This method will find the actual current time, found in google.com's response header:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
                                initWithURL:[NSURL URLWithString:@"http://google.com"]];

[request setHTTPMethod:@"GET"];

NSHTTPURLResponse *httpResponse = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&httpResponse error:nil];
NSString *dateString = [[httpResponse allHeaderFields] objectForKey:@"Date"];
NSDate *currentDate = [NSDate dateWithNaturalLanguageString:dateString locale:NSLocale.currentLocale];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!