9

I noticed that if I set my device time manually, and turn off the automatic time sync on my iOS device, [NSDate date] returns the date and time assuming the device time is correct--which it may not be.

Since the docs mention that NSDate has some sort of sync with NTP, I am wondering if there is any built-in way to get the accurate date and time instead of having to assume the device date and time is correct.

Anton
  • 3,998
  • 25
  • 40
  • I find one valuable check is to simply make sure that the phone's time value is greater than the date you shipped your app (or some such), so that you eliminate the case where the date has reset to Jan 1, 1970 or whatever. In that case throw up a message "Set your clock, you idiot!" (Or words to that effect.) – Hot Licks Feb 19 '13 at 18:13
  • @HotLicks this will in no way ensure that the time is correct as the OP is asking. – twaldron Feb 19 '13 at 18:45
  • True, but it catches, especially, a lot of iPad Touches with the clock set totally wrong. – Hot Licks Feb 19 '13 at 19:04
  • @HotLicks I do see value in having this check, although this whole discussion and answers make me want to re-engineer the whole thing to not need accurate times as there seems to be no solution without 3rd-party code. – Anton Feb 19 '13 at 19:42
  • @HotLicks fair enough :) – twaldron Feb 19 '13 at 19:42

2 Answers2

3

Perhaps https://github.com/jbenet/ios-ntp can help you? It's a library that can fetch the date and time from a time server.

Cthutu
  • 8,713
  • 7
  • 33
  • 49
1

I tried ios-ntp but didn't get expected results, so I found another library which is working fine and really easy to implement.

NHNetworkTime

Pods:

pod 'NHNetworkTime'
pod 'CocoaAsyncSocket'

Simple to use Import this whenever you want to get time:

#import "NHNetworkTime.h"

Call synchronize in - application: didFinishLaunchingWithOptions: to update time from server when you launch app:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[NHNetworkClock sharedNetworkClock] synchronize];
    return YES;
}

then you can get network time when sync complete in anywhere in your source code:

NSDate *networkDate = [NSDate networkDate];

or add notification to re-update your UI in anywhere you want when time is updated:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkTimeSyncCompleteNotification:) name:kNHNetworkTimeSyncCompleteNotification object:nil];

Cheers !!! :)

Harish Pathak
  • 1,567
  • 1
  • 18
  • 32