How can I get the actual date and time if the device date and time are inaccurate?

◇◆丶佛笑我妖孽 提交于 2020-01-11 05:00:10

问题


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.


回答1:


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.




回答2:


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 !!! :)



来源:https://stackoverflow.com/questions/14964318/how-can-i-get-the-actual-date-and-time-if-the-device-date-and-time-are-inaccurat

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!