├── Example
└── NHNetworkTimeExample
│ ├── Podfile
│ ├── NHNetworkTimeExample.xcodeproj
│ ├── project.xcworkspace
│ │ ├── contents.xcworkspacedata
│ │ └── xcshareddata
│ │ │ └── IDEWorkspaceChecks.plist
│ └── project.pbxproj
│ ├── NHNetworkTimeExample.xcworkspace
│ ├── xcshareddata
│ │ └── IDEWorkspaceChecks.plist
│ └── contents.xcworkspacedata
│ ├── NHNetworkTimeExample
│ ├── ViewController.h
│ ├── AppDelegate.h
│ ├── main.m
│ ├── Assets.xcassets
│ │ └── AppIcon.appiconset
│ │ │ └── Contents.json
│ ├── Info.plist
│ ├── Base.lproj
│ │ ├── LaunchScreen.storyboard
│ │ └── Main.storyboard
│ ├── AppDelegate.m
│ └── ViewController.m
│ └── Podfile.lock
├── NHNetworkTime
├── NHNetworkTime.h
├── NHNTLog.h
├── NSDate+NetworkClock.m
├── NSDate+NetworkClock.h
├── NHNetworkClock.h
├── NHNetAssociation.h
├── NHNetworkClock.m
└── NHNetAssociation.m
├── .gitignore
├── NHNetworkTime.podspec
├── README.md
└── LICENSE
/Example/NHNetworkTimeExample/Podfile:
--------------------------------------------------------------------------------
1 | target 'NHNetworkTimeExample' do
2 | pod 'NHNetworkTime', :path => '../../'
3 | end
--------------------------------------------------------------------------------
/NHNetworkTime/NHNetworkTime.h:
--------------------------------------------------------------------------------
1 | /*
2 | NetworkClock.h
3 | Created by Gavin Eadie on Oct17/10
4 | Edited by Nguyen Cong Huy
5 | */
6 | #import "NHNTLog.h"
7 | #import "NHNetAssociation.h"
8 | #import "NHNetworkClock.h"
9 | #import "NSDate+NetworkClock.h"
10 |
--------------------------------------------------------------------------------
/Example/NHNetworkTimeExample/NHNetworkTimeExample.xcodeproj/project.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Example/NHNetworkTimeExample/NHNetworkTimeExample.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/Example/NHNetworkTimeExample/NHNetworkTimeExample.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/Example/NHNetworkTimeExample/NHNetworkTimeExample/ViewController.h:
--------------------------------------------------------------------------------
1 | //
2 | // ViewController.h
3 | // NHNetworkTimeExample
4 | //
5 | // Created by Nguyen Cong Huy on 9/20/15.
6 | // Copyright © 2015 Nguyen Cong Huy. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface ViewController : UIViewController
12 |
13 |
14 | @end
15 |
16 |
--------------------------------------------------------------------------------
/Example/NHNetworkTimeExample/NHNetworkTimeExample.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/Example/NHNetworkTimeExample/NHNetworkTimeExample/AppDelegate.h:
--------------------------------------------------------------------------------
1 | //
2 | // AppDelegate.h
3 | // NHNetworkTimeExample
4 | //
5 | // Created by Nguyen Cong Huy on 9/20/15.
6 | // Copyright © 2015 Nguyen Cong Huy. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface AppDelegate : UIResponder
12 |
13 | @property (strong, nonatomic) UIWindow *window;
14 |
15 |
16 | @end
17 |
18 |
--------------------------------------------------------------------------------
/Example/NHNetworkTimeExample/NHNetworkTimeExample/main.m:
--------------------------------------------------------------------------------
1 | //
2 | // main.m
3 | // NHNetworkTimeExample
4 | //
5 | // Created by Nguyen Cong Huy on 9/20/15.
6 | // Copyright © 2015 Nguyen Cong Huy. All rights reserved.
7 | //
8 |
9 | #import
10 | #import "AppDelegate.h"
11 |
12 | int main(int argc, char * argv[]) {
13 | @autoreleasepool {
14 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/NHNetworkTime/NHNTLog.h:
--------------------------------------------------------------------------------
1 | #import
2 | #import
3 |
4 | #define NTP_Logging(fmt, ...)
5 | #define LogInProduction(fmt, ...) \
6 | NSLog((@"%@|" fmt), [NSString stringWithFormat: @"%16s", \
7 | [[[self class] description] UTF8String]], ##__VA_ARGS__)
8 |
9 | #ifdef IOS_NTP_LOGGING
10 | #undef NTP_Logging
11 | #define NTP_Logging(fmt, ...) \
12 | NSLog((@"%@|" fmt), [NSString stringWithFormat: @"%16s", \
13 | [[[self class] description] UTF8String]], ##__VA_ARGS__)
14 | #endif
15 |
--------------------------------------------------------------------------------
/Example/NHNetworkTimeExample/Podfile.lock:
--------------------------------------------------------------------------------
1 | PODS:
2 | - CocoaAsyncSocket (7.5.0):
3 | - CocoaAsyncSocket/GCD (= 7.5.0)
4 | - CocoaAsyncSocket/GCD (7.5.0)
5 | - NHNetworkTime (1.7):
6 | - CocoaAsyncSocket (~> 7.5.0)
7 |
8 | DEPENDENCIES:
9 | - NHNetworkTime (from `../../`)
10 |
11 | EXTERNAL SOURCES:
12 | NHNetworkTime:
13 | :path: ../../
14 |
15 | SPEC CHECKSUMS:
16 | CocoaAsyncSocket: 3baeb1ddd969f81cf9fca81053ae49ef2d1cbbfa
17 | NHNetworkTime: b140ee21770aed41e7b8fd43647bce6349ad10f2
18 |
19 | PODFILE CHECKSUM: 18bb4b225dff96cdf16db3cea747adc903a9705d
20 |
21 | COCOAPODS: 1.0.1
22 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Xcode
2 | #
3 | build/
4 | *.pbxuser
5 | !default.pbxuser
6 | *.mode1v3
7 | !default.mode1v3
8 | *.mode2v3
9 | !default.mode2v3
10 | *.perspectivev3
11 | !default.perspectivev3
12 | xcuserdata
13 | *.xccheckout
14 | *.moved-aside
15 | DerivedData
16 | *.hmap
17 | *.ipa
18 | *.xcuserstate
19 |
20 | # CocoaPods
21 | #
22 | # We recommend against adding the Pods directory to your .gitignore. However
23 | # you should judge for yourself, the pros and cons are mentioned at:
24 | # http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control
25 | #
26 | #Pods/
27 | Example/NHNetworkTimeExample/Pods
28 |
--------------------------------------------------------------------------------
/NHNetworkTime.podspec:
--------------------------------------------------------------------------------
1 | Pod::Spec.new do |s|
2 | s.name = 'NHNetworkTime'
3 | s.version = '1.7.1'
4 | s.summary = 'Simple Network Time Protocol SNTP for iOS.'
5 | s.homepage = 'https://github.com/huynguyencong/NHNetworkTime'
6 | s.license = { :type => 'Apache', :file => 'LICENSE' }
7 | s.source = { :git => 'https://github.com/huynguyencong/NHNetworkTime.git', :tag => "#{s.version}" }
8 | s.author = { 'Huy Nguyen Cong' => 'https://github.com/huynguyencong' }
9 | s.ios.deployment_target = '7.0'
10 | s.source_files = 'NHNetworkTime/*.{h,m}'
11 | s.framework = 'CFNetwork'
12 | s.dependency 'CocoaAsyncSocket', '~>7.5.0'
13 | s.requires_arc = true
14 | end
15 |
--------------------------------------------------------------------------------
/NHNetworkTime/NSDate+NetworkClock.m:
--------------------------------------------------------------------------------
1 |
2 |
3 | #import "NSDate+NetworkClock.h"
4 |
5 | @implementation NSDate (NetworkClock)
6 |
7 | - (NSTimeInterval) timeIntervalSinceNetworkDate {
8 | return [self timeIntervalSinceDate:[NSDate networkDate]];
9 | }
10 |
11 | + (NSTimeInterval) timeIntervalSinceNetworkDate {
12 | return [[self date] timeIntervalSinceNetworkDate];
13 | }
14 |
15 |
16 | + (NSDate *) networkDate {
17 | return [[NHNetworkClock sharedNetworkClock] networkTime];
18 | }
19 |
20 | + (NSDate *) threadsafeNetworkDate {
21 | NHNetworkClock *sharedClock = [NHNetworkClock sharedNetworkClock];
22 | @synchronized(sharedClock) {
23 | return [sharedClock networkTime];
24 | }
25 | }
26 |
27 |
28 | @end
--------------------------------------------------------------------------------
/NHNetworkTime/NSDate+NetworkClock.h:
--------------------------------------------------------------------------------
1 |
2 | // Author: Juan Batiz-Benet
3 |
4 | // Category on NSDate to provide convenience access to NetworkClock.
5 | // To use, simply call [NSDate networkDate];
6 |
7 | #import
8 | #import "NHNetworkClock.h"
9 |
10 |
11 | @interface NSDate (NetworkClock)
12 |
13 | @property (NS_NONATOMIC_IOSONLY, readonly) NSTimeInterval timeIntervalSinceNetworkDate;
14 |
15 | + (NSTimeInterval)timeIntervalSinceNetworkDate;
16 |
17 | + (NSDate *)networkDate;
18 |
19 | // the threadsafe version guards against reading a double that could be
20 | // potentially being updated at the same time. Since doubles are 8 words,
21 | // and arm is 32bit, this is not atomic and could provide bad values.
22 |
23 | + (NSDate *)threadsafeNetworkDate;
24 |
25 | @end
--------------------------------------------------------------------------------
/Example/NHNetworkTimeExample/NHNetworkTimeExample/Assets.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "iphone",
5 | "size" : "29x29",
6 | "scale" : "2x"
7 | },
8 | {
9 | "idiom" : "iphone",
10 | "size" : "29x29",
11 | "scale" : "3x"
12 | },
13 | {
14 | "idiom" : "iphone",
15 | "size" : "40x40",
16 | "scale" : "2x"
17 | },
18 | {
19 | "idiom" : "iphone",
20 | "size" : "40x40",
21 | "scale" : "3x"
22 | },
23 | {
24 | "idiom" : "iphone",
25 | "size" : "60x60",
26 | "scale" : "2x"
27 | },
28 | {
29 | "idiom" : "iphone",
30 | "size" : "60x60",
31 | "scale" : "3x"
32 | },
33 | {
34 | "idiom" : "ipad",
35 | "size" : "29x29",
36 | "scale" : "1x"
37 | },
38 | {
39 | "idiom" : "ipad",
40 | "size" : "29x29",
41 | "scale" : "2x"
42 | },
43 | {
44 | "idiom" : "ipad",
45 | "size" : "40x40",
46 | "scale" : "1x"
47 | },
48 | {
49 | "idiom" : "ipad",
50 | "size" : "40x40",
51 | "scale" : "2x"
52 | },
53 | {
54 | "idiom" : "ipad",
55 | "size" : "76x76",
56 | "scale" : "1x"
57 | },
58 | {
59 | "idiom" : "ipad",
60 | "size" : "76x76",
61 | "scale" : "2x"
62 | },
63 | {
64 | "idiom" : "ipad",
65 | "size" : "83.5x83.5",
66 | "scale" : "2x"
67 | }
68 | ],
69 | "info" : {
70 | "version" : 1,
71 | "author" : "xcode"
72 | }
73 | }
--------------------------------------------------------------------------------
/NHNetworkTime/NHNetworkClock.h:
--------------------------------------------------------------------------------
1 | /**
2 | NHNetworkClock.h
3 | Created by Gavin Eadie on Oct17/10 ... Copyright 2010-14 Ramsay Consulting. All rights reserved.
4 | Modified by Nguyen Cong Huy on 9 Sep 2015
5 | */
6 |
7 | #import "NHNetAssociation.h"
8 |
9 | #define kNHNetworkTimeSyncCompleteNotification @"kNHNetworkTimeSyncCompleteNotification"
10 |
11 | // The NetworkClock sends notifications of the network time. It will attempt to provide a very early estimate and then refine that and reduce the number of notifications ...
12 | // NetworkClock is a singleton class which will provide the best estimate of the difference in time between the device's system clock and the time returned by a collection of time servers. The method returns an NSDate with the network time.
13 |
14 | @interface NHNetworkClock : NSObject
15 |
16 | @property (nonatomic, readonly, copy) NSDate *networkTime;
17 | @property (nonatomic, readonly) NSTimeInterval networkOffset;
18 | @property (nonatomic, readonly) BOOL isSynchronized;
19 |
20 | #pragma mark - Options
21 |
22 | // every time network time is synchronized with server, it will be saved to disk. When call sync function (synchronize), if this property set to YES, it will use the previous saved time, before receive synchronized time from server. Default is YES
23 | @property (nonatomic) BOOL shouldUseSavedSynchronizedTime;
24 |
25 | // synchronize if user change local time
26 | @property (nonatomic) BOOL isAutoSynchronizedWhenUserChangeLocalTime;
27 |
28 | #pragma mark -
29 |
30 | + (instancetype) sharedNetworkClock;
31 |
32 | - (void)synchronize;
33 |
34 | @end
--------------------------------------------------------------------------------
/Example/NHNetworkTimeExample/NHNetworkTimeExample/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIdentifier
10 | $(PRODUCT_BUNDLE_IDENTIFIER)
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | $(PRODUCT_NAME)
15 | CFBundlePackageType
16 | APPL
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleSignature
20 | ????
21 | CFBundleVersion
22 | 1
23 | LSRequiresIPhoneOS
24 |
25 | UILaunchStoryboardName
26 | LaunchScreen
27 | UIMainStoryboardFile
28 | Main
29 | UIRequiredDeviceCapabilities
30 |
31 | armv7
32 |
33 | UISupportedInterfaceOrientations
34 |
35 | UIInterfaceOrientationPortrait
36 | UIInterfaceOrientationLandscapeLeft
37 | UIInterfaceOrientationLandscapeRight
38 |
39 | UISupportedInterfaceOrientations~ipad
40 |
41 | UIInterfaceOrientationPortrait
42 | UIInterfaceOrientationPortraitUpsideDown
43 | UIInterfaceOrientationLandscapeLeft
44 | UIInterfaceOrientationLandscapeRight
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/Example/NHNetworkTimeExample/NHNetworkTimeExample/Base.lproj/LaunchScreen.storyboard:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/Example/NHNetworkTimeExample/NHNetworkTimeExample/AppDelegate.m:
--------------------------------------------------------------------------------
1 | //
2 | // AppDelegate.m
3 | // NHNetworkTimeExample
4 | //
5 | // Created by Nguyen Cong Huy on 9/20/15.
6 | // Copyright © 2015 Nguyen Cong Huy. All rights reserved.
7 | //
8 |
9 | #import "AppDelegate.h"
10 | #import "NHNetworkTime.h"
11 |
12 | @interface AppDelegate ()
13 |
14 | @end
15 |
16 | @implementation AppDelegate
17 |
18 |
19 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
20 | [[NHNetworkClock sharedNetworkClock] synchronize];
21 | return YES;
22 | }
23 |
24 | - (void)applicationWillResignActive:(UIApplication *)application {
25 | // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
26 | // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
27 | }
28 |
29 | - (void)applicationDidEnterBackground:(UIApplication *)application {
30 | // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
31 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
32 | }
33 |
34 | - (void)applicationWillEnterForeground:(UIApplication *)application {
35 | // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
36 | }
37 |
38 | - (void)applicationDidBecomeActive:(UIApplication *)application {
39 | // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
40 | }
41 |
42 | - (void)applicationWillTerminate:(UIApplication *)application {
43 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
44 | }
45 |
46 | @end
47 |
--------------------------------------------------------------------------------
/NHNetworkTime/NHNetAssociation.h:
--------------------------------------------------------------------------------
1 | /**
2 | NHNetAssociation.h
3 | Created by Gavin Eadie on Nov03/10 ... Copyright 2010-14 Ramsay Consulting. All rights reserved.
4 | Modified by Nguyen Cong Huy on 9 Sep 2015
5 |
6 | This NetAssociation manages the communication and time calculations for one server.
7 | Multiple servers are used in a process in which each client/server pair (association) works to obtain its own best version of the time. The client sends small UDP packets to the server and the server overwrites certain fields in the packet and returns it immediately. As each packet is received, the offset between the client's network time and the system clock is derived with associated statistics delta, epsilon, and psi.
8 | Each association makes a best effort at obtaining an accurate time and makes it available as a property. Another process may use this to select, cluster, and combine the various servers' data to determine the most accurate and reliable candidates to provide an overall best time.
9 | */
10 |
11 | #import
12 | #import
13 |
14 |
15 |
16 | #import
17 |
18 | @protocol NHNetAssociationDelegate;
19 |
20 | @interface NHNetAssociation : NSObject
21 |
22 | @property (readonly) NSString *server; // server name "123.45.67.89"
23 | @property (readonly) BOOL active; // is this clock running yet?
24 | @property (readonly) BOOL trusty; // is this clock trustworthy
25 | @property (readonly) double offset; // offset from device time (secs)
26 | @property (weak) id delegate;
27 |
28 | - (instancetype) initWithServerName:(NSString *) serverName;
29 |
30 | // This sets the association in a mode where it repeatedly gets time from its server and performs statical check and averages on these multiple values to provide a more accurate time. Starts the timer firing (sets the fire time randonly within the next five seconds) ...
31 | - (void)enable;
32 |
33 | //This stops the timer firing (sets the fire time to the infinite future) ...
34 | - (void)finish;
35 |
36 | // send one datagram to server ..
37 | - (void)sendTimeQuery;
38 |
39 | @end
40 |
41 | @protocol NHNetAssociationDelegate
42 |
43 | - (void)netAssociationDidFinishGetTime:(NHNetAssociation *)netAssociation;
44 |
45 | @end
--------------------------------------------------------------------------------
/Example/NHNetworkTimeExample/NHNetworkTimeExample/ViewController.m:
--------------------------------------------------------------------------------
1 | //
2 | // ViewController.m
3 | // NHNetworkTimeExample
4 | //
5 | // Created by Nguyen Cong Huy on 9/20/15.
6 | // Copyright © 2015 Nguyen Cong Huy. All rights reserved.
7 | //
8 |
9 | #import "ViewController.h"
10 | #import "NHNetworkTime.h"
11 |
12 | @interface ViewController ()
13 | @property (weak, nonatomic) IBOutlet UILabel *currentLabel;
14 | @property (weak, nonatomic) IBOutlet UILabel *networkLabel;
15 | @property (weak, nonatomic) IBOutlet UILabel *syncedLabel;
16 |
17 | @property (nonatomic) NSTimer *oneSecondTimer;
18 |
19 | @end
20 |
21 | @implementation ViewController
22 |
23 | - (instancetype)init {
24 | if(self = [super init]) {
25 |
26 | }
27 | return self;
28 | }
29 |
30 | - (void)viewDidLoad {
31 | [super viewDidLoad];
32 | [self updateDateToLabel];
33 | [self observeTimeSyncNotification];
34 | [self createUpdateUITimer];
35 | }
36 |
37 | - (void)dealloc {
38 | [[NSNotificationCenter defaultCenter] removeObserver:self];
39 | [self.oneSecondTimer invalidate];
40 | }
41 |
42 | #pragma mark - Notification
43 |
44 | - (void)observeTimeSyncNotification {
45 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkTimeSyncCompleteNotification:) name:kNHNetworkTimeSyncCompleteNotification object:nil];
46 | }
47 |
48 | - (void)networkTimeSyncCompleteNotification:(NSNotification *)notification {
49 | [self updateDateToLabel];
50 | }
51 |
52 | #pragma mark - Update label timer
53 |
54 | - (void)createUpdateUITimer {
55 | self.oneSecondTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(oneSecondTimerTick) userInfo:nil repeats:YES];
56 | }
57 |
58 | - (void)oneSecondTimerTick {
59 | [self updateDateToLabel];
60 | }
61 |
62 | #pragma mark - UI
63 |
64 | - (void)updateDateToLabel {
65 | NSString *currentLabelText = [NSString stringWithFormat:@"%@", [[NSDate date] descriptionWithLocale:[NSLocale systemLocale]]];
66 | NSString *networkLabelText = [NSString stringWithFormat:@"%@", [[NSDate networkDate] descriptionWithLocale:[NSLocale systemLocale]]];
67 |
68 | self.currentLabel.text = currentLabelText;
69 | self.networkLabel.text = networkLabelText;
70 |
71 | if([NHNetworkClock sharedNetworkClock].isSynchronized) {
72 | self.syncedLabel.text = @"Time is SYNCHRONIZED";
73 | self.syncedLabel.textColor = [UIColor blueColor];
74 | }
75 | else {
76 | self.syncedLabel.text = @"Time is NOT synchronized";
77 | self.syncedLabel.textColor = [UIColor redColor];
78 | }
79 | }
80 |
81 | @end
82 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # NHNetworkTime
2 | A network time protocol (NTP) client.
3 |
4 | ### About
5 |
6 | The clock on the oldest iPhone, iTouch or iPad is not closely synchronized to the correct time. In the case of a device which is obtaining its time from the telephone system, there is a setting to enable synchronizing to the phone company time, but that time has been known to be over a minute different from the correct time.
7 |
8 | In addition, users may change their device time and severely affect applications that rely on correct times to enforce functionality, or may set their devices clock into the past in an attempt to dodge an expiry date.
9 |
10 | This project contains code to provide time obtained from standard time servers using the simple network time protocol (SNTP: RFC 5905). The implementation is not a rigorous as described in that document since the goal was to improve time accuracy to tens of milliSeconds, not to microseconds.
11 |
12 | Computers using the NTP protocol usually employ it in a continuous low level task to keep track of the time on a continuous basis. A background application uses occasional time estimates from a set of time servers to determine the best time by sampling these values over time. iOS applications are different, being more likely to want a one-time, quick estimate of the time.
13 |
14 | #### Compatible
15 | - iOS 7 and later.
16 | - Objective C, and Swift with bridge header (read below guide)
17 |
18 | ### Usage
19 |
20 | #### Cocoapod
21 | Add below line to Podfile:
22 |
23 | ```
24 | pod NHNetworkTime
25 | ```
26 | and then run below command in Terminal to install:
27 | `pod install`
28 |
29 | Note: If above pod isn't working, try using below pod defination in Podfile:
30 | `pod 'NHNetworkTime', :git => 'https://github.com/huynguyencong/NHNetworkTime.git'`
31 | #### Manual
32 | Add all file in folder NHNetworkTime to your project. Then add `CocoaAsyncSocket` use Cocoapod or add manual.
33 |
34 | #### Simple to use
35 | Import this whenever you want to get time:
36 |
37 | ```
38 | #import "NHNetworkTime.h"
39 | ```
40 |
41 | Call `synchronize` in `- application: didFinishLaunchingWithOptions:` to update time from server when you launch app:
42 |
43 | ```
44 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
45 | [[NHNetworkClock sharedNetworkClock] synchronize];
46 | return YES;
47 | }
48 | ```
49 |
50 | then you can get network time when sync complete in anywhere in your source code:
51 |
52 | ```
53 | NSDate *networkDate = [NSDate networkDate];
54 | ```
55 |
56 | or add notification to re-update your UI in anywhere you want when time is updated:
57 |
58 | ```
59 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkTimeSyncCompleteNotification:) name:kNHNetworkTimeSyncCompleteNotification object:nil];
60 | ```
61 |
62 | #### Swift
63 | #####Use `use_frameworks!`
64 |
65 | If you have `use_frameworks!` option in Podfile, import `NHNetworkTime` framework in each code file use `NHNetworkTime` objects:
66 |
67 | ```
68 | @import NHNetworkTime
69 | ```
70 |
71 |
72 | ##### Not use `use_frameworks!`
73 |
74 |
75 | Import `NHNetworkTime.h` to your in bridge header file:
76 |
77 | ```
78 | #import
79 | ```
80 | * You can create bridge header file by create an Objective C file in project. Xcode will ask you to create bridge header file. After, you can delete the temporatory Objective C file have just added, and import `NHNetworkTime.h` into there (Read more: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html)
81 |
82 | ##### In your code
83 | Now, you can call below code in your code:
84 |
85 | ```
86 | NHNetworkClock.sharedNetworkClock().synchronize()
87 | ```
88 | and:
89 |
90 | ```
91 | NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("syncCompleteNotification"), name: kNHNetworkTimeSyncCompleteNotification, object: nil)
92 | ```
93 | #### More from NHNetworkClock
94 | - Use `NSNotifcationCenter` to add observer `kNHNetworkTimeSyncCompleteNotification` to receive notification when time sync complete
95 | - Property `isSynchronized`: Check network time synchronized or not
96 | - Property `shouldUseSavedSynchronizedTime`: Should use offset time saved in the last synchronization before sync from server. Default is YES.
97 | - Property `isAutoSynchronizedWhenUserChangeLocalTime`: Is auto sync when user change local time. Default is YES.
98 |
99 | #### Custom time server
100 | Add to project file name `ntp.hosts`, with content is time server address in every line. If file is not exist, it will use default time server. Example for `ntp.hosts` file:
101 |
102 | ```
103 | asia.pool.ntp.org
104 | europe.pool.ntp.org
105 | north-america.pool.ntp.org
106 | ```
107 |
108 |
109 | ### About this source
110 | NHNetworkTime is built from ios ntp open source from jbenet. NHNetworkTime fixed a critical bug get wrong time from origin source, and added more improvements:
111 |
112 | - Post notification when sync complete
113 | - Property make you know whether sync complete or not
114 | - Save offset time local to use immediately right after launch app, don't have to waiting for server
115 | - Auto sync when user change local time
116 |
117 | ### License
118 | NHNetworkTime is released under the Apache license. See LICENSE for details. Copyright © Nguyen Cong Huy
119 |
--------------------------------------------------------------------------------
/NHNetworkTime/NHNetworkClock.m:
--------------------------------------------------------------------------------
1 | #import
2 |
3 | #import "NHNetworkClock.h"
4 | #import "NHNTLog.h"
5 |
6 | #define kTimeOffsetKey @"kTimeOffsetKey"
7 |
8 | @interface NHNetworkClock ()
9 |
10 | @property NSMutableArray *timeAssociations;
11 | @property NSArray *sortDescriptors;
12 | @property NSSortDescriptor *dispersionSortDescriptor;
13 | @property dispatch_queue_t associationDelegateQueue;
14 | @property (readwrite) BOOL isSynchronized;
15 |
16 | @end
17 |
18 | @implementation NHNetworkClock
19 |
20 | + (instancetype)sharedNetworkClock {
21 | static id sharedNetworkClockInstance = nil;
22 | static dispatch_once_t onceToken;
23 |
24 | dispatch_once(&onceToken, ^{
25 | sharedNetworkClockInstance = [[self alloc] init];
26 | });
27 |
28 | return sharedNetworkClockInstance;
29 | }
30 |
31 | - (instancetype)init {
32 | if (self = [super init]) {
33 | self.sortDescriptors = @[[[NSSortDescriptor alloc] initWithKey:@"dispersion" ascending:YES]];
34 | self.timeAssociations = [NSMutableArray arrayWithCapacity:100];
35 | self.shouldUseSavedSynchronizedTime = YES;
36 | self.isAutoSynchronizedWhenUserChangeLocalTime = YES;
37 |
38 | [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationSignificantTimeChangeNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
39 | if(self.isAutoSynchronizedWhenUserChangeLocalTime) {
40 | [self synchronize];
41 | }
42 | }];
43 | }
44 |
45 | return self;
46 | }
47 |
48 | - (void)dealloc {
49 | [[NSNotificationCenter defaultCenter] removeObserver:self];
50 | }
51 |
52 | - (void)reset {
53 | self.isSynchronized = NO;
54 | [self finishAssociations];
55 | [self.timeAssociations removeAllObjects];
56 | }
57 |
58 | // Return the offset to network-derived UTC.
59 |
60 | - (NSTimeInterval)networkOffset {
61 |
62 | double timeInterval = 0.0;
63 | short usefulCount = 0;
64 |
65 | if(self.timeAssociations.count > 0) {
66 |
67 | NSArray *sortedArray = [[self.timeAssociations sortedArrayUsingDescriptors:self.sortDescriptors] filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id _Nonnull evaluatedObject, NSDictionary * _Nullable bindings) {
68 | return [evaluatedObject isKindOfClass:[NHNetAssociation class]];
69 | }]];
70 |
71 | for (NHNetAssociation * timeAssociation in sortedArray) {
72 | if (timeAssociation.active) {
73 | if (timeAssociation.trusty) {
74 | usefulCount++;
75 | timeInterval = timeInterval + timeAssociation.offset;
76 | }
77 | else {
78 | if ([self.timeAssociations count] > 8) {
79 | [self.timeAssociations removeObject:timeAssociation];
80 | [timeAssociation finish];
81 | }
82 | }
83 |
84 | if (usefulCount == 8) break; // use 8 best dispersions
85 | }
86 | }
87 | }
88 |
89 | if (usefulCount > 0) {
90 | timeInterval = timeInterval / usefulCount;
91 | }
92 | else {
93 | if(self.shouldUseSavedSynchronizedTime) {
94 | timeInterval = [[NSUserDefaults standardUserDefaults] doubleForKey:kTimeOffsetKey];
95 | }
96 | }
97 |
98 | return timeInterval;
99 | }
100 |
101 | #pragma mark - Get time
102 |
103 | - (NSDate *)networkTime {
104 | return [[NSDate date] dateByAddingTimeInterval:-[self networkOffset]];
105 | }
106 |
107 | #pragma mark - Associations
108 |
109 | // Use the following time servers or, if it exists, read the "ntp.hosts" file from the application resources and derive all the IP addresses referred to, remove any duplicates and create an 'association' (individual host client) for each one.
110 |
111 | - (void)createAssociations {
112 | @synchronized(self) {
113 | NSArray *ntpDomains;
114 | NSString *filePath = [[NSBundle mainBundle] pathForResource:@"ntp.hosts" ofType:@""];
115 | if (nil == filePath) {
116 | ntpDomains = @[@"0.pool.ntp.org",
117 | @"0.uk.pool.ntp.org",
118 | @"0.us.pool.ntp.org",
119 | @"asia.pool.ntp.org",
120 | @"europe.pool.ntp.org",
121 | @"north-america.pool.ntp.org",
122 | @"south-america.pool.ntp.org",
123 | @"oceania.pool.ntp.org",
124 | @"africa.pool.ntp.org"];
125 | }
126 | else {
127 | NSString *fileData = [[NSString alloc] initWithData:[[NSFileManager defaultManager]
128 | contentsAtPath:filePath]
129 | encoding:NSUTF8StringEncoding];
130 |
131 | ntpDomains = [fileData componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
132 | }
133 |
134 | // for each NTP service domain name in the 'ntp.hosts' file : "0.pool.ntp.org" etc ...
135 | NSMutableSet *hostAddresses = [NSMutableSet setWithCapacity:100];
136 |
137 | for (NSString *ntpDomainName in ntpDomains) {
138 | if ([ntpDomainName length] == 0 ||
139 | [ntpDomainName characterAtIndex:0] == ' ' ||
140 | [ntpDomainName characterAtIndex:0] == '#') {
141 | continue;
142 | }
143 |
144 | // ... resolve the IP address of the named host : "0.pool.ntp.org" --> [123.45.67.89], ...
145 | CFHostRef ntpHostName = CFHostCreateWithName (nil, (__bridge CFStringRef)ntpDomainName);
146 | if (nil == ntpHostName) {
147 | NTP_Logging(@"CFHostCreateWithName for %@", ntpDomainName);
148 | continue; // couldn't create 'host object' ...
149 | }
150 |
151 | CFStreamError nameError;
152 | if (!CFHostStartInfoResolution (ntpHostName, kCFHostAddresses, &nameError)) {
153 | NTP_Logging(@"CFHostStartInfoResolution error %i for %@", (int)nameError.error, ntpDomainName);
154 | CFRelease(ntpHostName);
155 | continue; // couldn't start resolution ...
156 | }
157 |
158 | Boolean nameFound;
159 | CFArrayRef ntpHostAddrs = CFHostGetAddressing (ntpHostName, &nameFound);
160 |
161 | if (!nameFound) {
162 | NTP_Logging(@"CFHostGetAddressing: %@ NOT resolved", ntpHostName);
163 | CFRelease(ntpHostName);
164 | continue; // resolution failed ...
165 | }
166 |
167 | if (ntpHostAddrs == nil) {
168 | NTP_Logging(@"CFHostGetAddressing: no addresses resolved for %@", ntpHostName);
169 | CFRelease(ntpHostName);
170 | continue; // NO addresses were resolved ...
171 | }
172 | //for each (sockaddr structure wrapped by a CFDataRef/NSData *) associated with the hostname, drop the IP address string into a Set to remove duplicates.
173 | for (NSData *ntpHost in (__bridge NSArray *)ntpHostAddrs) {
174 | [hostAddresses addObject:[GCDAsyncUdpSocket hostFromAddress:ntpHost]];
175 | }
176 |
177 | CFRelease(ntpHostName);
178 | }
179 |
180 | NTP_Logging(@"%@", hostAddresses); // all the addresses resolved
181 |
182 | // ... now start one 'association' (network clock server) for each address.
183 | for (NSString *server in hostAddresses) {
184 | NHNetAssociation * timeAssociation = [[NHNetAssociation alloc] initWithServerName:server];
185 | timeAssociation.delegate = self;
186 |
187 | [self.timeAssociations addObject:timeAssociation];
188 | [timeAssociation enable]; // starts are randomized internally
189 | }
190 | }
191 | }
192 |
193 | // Stop all the individual ntp clients associations ..
194 |
195 | - (void)finishAssociations {
196 | NSArray *timeAssociationsCopied = [self.timeAssociations copy];
197 | for (NHNetAssociation * timeAssociation in timeAssociationsCopied) {
198 | timeAssociation.delegate = nil;
199 | [timeAssociation finish];
200 | }
201 |
202 | [[NSNotificationCenter defaultCenter] removeObserver:self];
203 | }
204 |
205 | #pragma mark - Sync
206 |
207 | - (void)synchronize {
208 | [self reset];
209 |
210 | [[[NSOperationQueue alloc] init] addOperation:[[NSInvocationOperation alloc]
211 | initWithTarget:self
212 | selector:@selector(createAssociations)
213 | object:nil]];
214 | }
215 |
216 | #pragma mark - NHNetAssociationDelegate
217 |
218 | - (void)netAssociationDidFinishGetTime:(NHNetAssociation *)netAssociation {
219 | if(netAssociation.active && netAssociation.trusty) {
220 |
221 | [[NSUserDefaults standardUserDefaults] setDouble:netAssociation.offset forKey:kTimeOffsetKey];
222 |
223 | if (self.isSynchronized == NO) {
224 | [[NSNotificationCenter defaultCenter] postNotificationName:kNHNetworkTimeSyncCompleteNotification object:nil userInfo:nil];
225 | self.isSynchronized = YES;
226 | }
227 | }
228 | }
229 |
230 | @end
231 |
--------------------------------------------------------------------------------
/Example/NHNetworkTimeExample/NHNetworkTimeExample/Base.lproj/Main.storyboard:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
26 |
32 |
37 |
43 |
49 |
55 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/Example/NHNetworkTimeExample/NHNetworkTimeExample.xcodeproj/project.pbxproj:
--------------------------------------------------------------------------------
1 | // !$*UTF8*$!
2 | {
3 | archiveVersion = 1;
4 | classes = {
5 | };
6 | objectVersion = 46;
7 | objects = {
8 |
9 | /* Begin PBXBuildFile section */
10 | 07D41A97C915FAF5A1E7B990 /* libPods-NHNetworkTimeExample.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 37C2022E48617CD49F4000B3 /* libPods-NHNetworkTimeExample.a */; };
11 | 6145E9A01BAE61930090DEC0 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 6145E99F1BAE61930090DEC0 /* main.m */; };
12 | 6145E9A31BAE61930090DEC0 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 6145E9A21BAE61930090DEC0 /* AppDelegate.m */; };
13 | 6145E9A61BAE61930090DEC0 /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 6145E9A51BAE61930090DEC0 /* ViewController.m */; };
14 | 6145E9A91BAE61930090DEC0 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 6145E9A71BAE61930090DEC0 /* Main.storyboard */; };
15 | 6145E9AB1BAE61930090DEC0 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 6145E9AA1BAE61930090DEC0 /* Assets.xcassets */; };
16 | 6145E9AE1BAE61930090DEC0 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 6145E9AC1BAE61930090DEC0 /* LaunchScreen.storyboard */; };
17 | /* End PBXBuildFile section */
18 |
19 | /* Begin PBXFileReference section */
20 | 37C2022E48617CD49F4000B3 /* libPods-NHNetworkTimeExample.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-NHNetworkTimeExample.a"; sourceTree = BUILT_PRODUCTS_DIR; };
21 | 3F11F492A4C185ACADBF4CD9 /* Pods-NHNetworkTimeExample.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-NHNetworkTimeExample.release.xcconfig"; path = "Pods/Target Support Files/Pods-NHNetworkTimeExample/Pods-NHNetworkTimeExample.release.xcconfig"; sourceTree = ""; };
22 | 588492C0B1BA299603B92822 /* Pods-NHNetworkTimeExample.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-NHNetworkTimeExample.debug.xcconfig"; path = "Pods/Target Support Files/Pods-NHNetworkTimeExample/Pods-NHNetworkTimeExample.debug.xcconfig"; sourceTree = ""; };
23 | 6145E99B1BAE61930090DEC0 /* NHNetworkTimeExample.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = NHNetworkTimeExample.app; sourceTree = BUILT_PRODUCTS_DIR; };
24 | 6145E99F1BAE61930090DEC0 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; };
25 | 6145E9A11BAE61930090DEC0 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; };
26 | 6145E9A21BAE61930090DEC0 /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; };
27 | 6145E9A41BAE61930090DEC0 /* ViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ViewController.h; sourceTree = ""; };
28 | 6145E9A51BAE61930090DEC0 /* ViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ViewController.m; sourceTree = ""; };
29 | 6145E9A81BAE61930090DEC0 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; };
30 | 6145E9AA1BAE61930090DEC0 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; };
31 | 6145E9AD1BAE61930090DEC0 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; };
32 | 6145E9AF1BAE61930090DEC0 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; };
33 | /* End PBXFileReference section */
34 |
35 | /* Begin PBXFrameworksBuildPhase section */
36 | 6145E9981BAE61930090DEC0 /* Frameworks */ = {
37 | isa = PBXFrameworksBuildPhase;
38 | buildActionMask = 2147483647;
39 | files = (
40 | 07D41A97C915FAF5A1E7B990 /* libPods-NHNetworkTimeExample.a in Frameworks */,
41 | );
42 | runOnlyForDeploymentPostprocessing = 0;
43 | };
44 | /* End PBXFrameworksBuildPhase section */
45 |
46 | /* Begin PBXGroup section */
47 | 25BADC53032A061C6A56470D /* Pods */ = {
48 | isa = PBXGroup;
49 | children = (
50 | 588492C0B1BA299603B92822 /* Pods-NHNetworkTimeExample.debug.xcconfig */,
51 | 3F11F492A4C185ACADBF4CD9 /* Pods-NHNetworkTimeExample.release.xcconfig */,
52 | );
53 | name = Pods;
54 | sourceTree = "";
55 | };
56 | 556FAE79A7668552BD5916BE /* Frameworks */ = {
57 | isa = PBXGroup;
58 | children = (
59 | 37C2022E48617CD49F4000B3 /* libPods-NHNetworkTimeExample.a */,
60 | );
61 | name = Frameworks;
62 | sourceTree = "";
63 | };
64 | 6145E9921BAE61930090DEC0 = {
65 | isa = PBXGroup;
66 | children = (
67 | 6145E99D1BAE61930090DEC0 /* NHNetworkTimeExample */,
68 | 6145E99C1BAE61930090DEC0 /* Products */,
69 | 25BADC53032A061C6A56470D /* Pods */,
70 | 556FAE79A7668552BD5916BE /* Frameworks */,
71 | );
72 | sourceTree = "";
73 | };
74 | 6145E99C1BAE61930090DEC0 /* Products */ = {
75 | isa = PBXGroup;
76 | children = (
77 | 6145E99B1BAE61930090DEC0 /* NHNetworkTimeExample.app */,
78 | );
79 | name = Products;
80 | sourceTree = "";
81 | };
82 | 6145E99D1BAE61930090DEC0 /* NHNetworkTimeExample */ = {
83 | isa = PBXGroup;
84 | children = (
85 | 6145E9A11BAE61930090DEC0 /* AppDelegate.h */,
86 | 6145E9A21BAE61930090DEC0 /* AppDelegate.m */,
87 | 6145E9A41BAE61930090DEC0 /* ViewController.h */,
88 | 6145E9A51BAE61930090DEC0 /* ViewController.m */,
89 | 6145E9A71BAE61930090DEC0 /* Main.storyboard */,
90 | 6145E9AA1BAE61930090DEC0 /* Assets.xcassets */,
91 | 6145E9AC1BAE61930090DEC0 /* LaunchScreen.storyboard */,
92 | 6145E9AF1BAE61930090DEC0 /* Info.plist */,
93 | 6145E99E1BAE61930090DEC0 /* Supporting Files */,
94 | );
95 | path = NHNetworkTimeExample;
96 | sourceTree = "";
97 | };
98 | 6145E99E1BAE61930090DEC0 /* Supporting Files */ = {
99 | isa = PBXGroup;
100 | children = (
101 | 6145E99F1BAE61930090DEC0 /* main.m */,
102 | );
103 | name = "Supporting Files";
104 | sourceTree = "";
105 | };
106 | /* End PBXGroup section */
107 |
108 | /* Begin PBXNativeTarget section */
109 | 6145E99A1BAE61930090DEC0 /* NHNetworkTimeExample */ = {
110 | isa = PBXNativeTarget;
111 | buildConfigurationList = 6145E9B21BAE61930090DEC0 /* Build configuration list for PBXNativeTarget "NHNetworkTimeExample" */;
112 | buildPhases = (
113 | 23672BC7DDCB891CFC52167F /* [CP] Check Pods Manifest.lock */,
114 | 6145E9971BAE61930090DEC0 /* Sources */,
115 | 6145E9981BAE61930090DEC0 /* Frameworks */,
116 | 6145E9991BAE61930090DEC0 /* Resources */,
117 | 672CA20F54FC1D974BABBAE7 /* [CP] Embed Pods Frameworks */,
118 | 723F952F49E1DB6C4172EC28 /* [CP] Copy Pods Resources */,
119 | );
120 | buildRules = (
121 | );
122 | dependencies = (
123 | );
124 | name = NHNetworkTimeExample;
125 | productName = NHNetworkTimeExample;
126 | productReference = 6145E99B1BAE61930090DEC0 /* NHNetworkTimeExample.app */;
127 | productType = "com.apple.product-type.application";
128 | };
129 | /* End PBXNativeTarget section */
130 |
131 | /* Begin PBXProject section */
132 | 6145E9931BAE61930090DEC0 /* Project object */ = {
133 | isa = PBXProject;
134 | attributes = {
135 | LastUpgradeCheck = 0700;
136 | ORGANIZATIONNAME = "Nguyen Cong Huy";
137 | TargetAttributes = {
138 | 6145E99A1BAE61930090DEC0 = {
139 | CreatedOnToolsVersion = 7.0;
140 | };
141 | };
142 | };
143 | buildConfigurationList = 6145E9961BAE61930090DEC0 /* Build configuration list for PBXProject "NHNetworkTimeExample" */;
144 | compatibilityVersion = "Xcode 3.2";
145 | developmentRegion = English;
146 | hasScannedForEncodings = 0;
147 | knownRegions = (
148 | en,
149 | Base,
150 | );
151 | mainGroup = 6145E9921BAE61930090DEC0;
152 | productRefGroup = 6145E99C1BAE61930090DEC0 /* Products */;
153 | projectDirPath = "";
154 | projectRoot = "";
155 | targets = (
156 | 6145E99A1BAE61930090DEC0 /* NHNetworkTimeExample */,
157 | );
158 | };
159 | /* End PBXProject section */
160 |
161 | /* Begin PBXResourcesBuildPhase section */
162 | 6145E9991BAE61930090DEC0 /* Resources */ = {
163 | isa = PBXResourcesBuildPhase;
164 | buildActionMask = 2147483647;
165 | files = (
166 | 6145E9AE1BAE61930090DEC0 /* LaunchScreen.storyboard in Resources */,
167 | 6145E9AB1BAE61930090DEC0 /* Assets.xcassets in Resources */,
168 | 6145E9A91BAE61930090DEC0 /* Main.storyboard in Resources */,
169 | );
170 | runOnlyForDeploymentPostprocessing = 0;
171 | };
172 | /* End PBXResourcesBuildPhase section */
173 |
174 | /* Begin PBXShellScriptBuildPhase section */
175 | 23672BC7DDCB891CFC52167F /* [CP] Check Pods Manifest.lock */ = {
176 | isa = PBXShellScriptBuildPhase;
177 | buildActionMask = 2147483647;
178 | files = (
179 | );
180 | inputPaths = (
181 | );
182 | name = "[CP] Check Pods Manifest.lock";
183 | outputPaths = (
184 | );
185 | runOnlyForDeploymentPostprocessing = 0;
186 | shellPath = /bin/sh;
187 | shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n";
188 | showEnvVarsInLog = 0;
189 | };
190 | 672CA20F54FC1D974BABBAE7 /* [CP] Embed Pods Frameworks */ = {
191 | isa = PBXShellScriptBuildPhase;
192 | buildActionMask = 2147483647;
193 | files = (
194 | );
195 | inputPaths = (
196 | );
197 | name = "[CP] Embed Pods Frameworks";
198 | outputPaths = (
199 | );
200 | runOnlyForDeploymentPostprocessing = 0;
201 | shellPath = /bin/sh;
202 | shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-NHNetworkTimeExample/Pods-NHNetworkTimeExample-frameworks.sh\"\n";
203 | showEnvVarsInLog = 0;
204 | };
205 | 723F952F49E1DB6C4172EC28 /* [CP] Copy Pods Resources */ = {
206 | isa = PBXShellScriptBuildPhase;
207 | buildActionMask = 2147483647;
208 | files = (
209 | );
210 | inputPaths = (
211 | );
212 | name = "[CP] Copy Pods Resources";
213 | outputPaths = (
214 | );
215 | runOnlyForDeploymentPostprocessing = 0;
216 | shellPath = /bin/sh;
217 | shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-NHNetworkTimeExample/Pods-NHNetworkTimeExample-resources.sh\"\n";
218 | showEnvVarsInLog = 0;
219 | };
220 | /* End PBXShellScriptBuildPhase section */
221 |
222 | /* Begin PBXSourcesBuildPhase section */
223 | 6145E9971BAE61930090DEC0 /* Sources */ = {
224 | isa = PBXSourcesBuildPhase;
225 | buildActionMask = 2147483647;
226 | files = (
227 | 6145E9A61BAE61930090DEC0 /* ViewController.m in Sources */,
228 | 6145E9A31BAE61930090DEC0 /* AppDelegate.m in Sources */,
229 | 6145E9A01BAE61930090DEC0 /* main.m in Sources */,
230 | );
231 | runOnlyForDeploymentPostprocessing = 0;
232 | };
233 | /* End PBXSourcesBuildPhase section */
234 |
235 | /* Begin PBXVariantGroup section */
236 | 6145E9A71BAE61930090DEC0 /* Main.storyboard */ = {
237 | isa = PBXVariantGroup;
238 | children = (
239 | 6145E9A81BAE61930090DEC0 /* Base */,
240 | );
241 | name = Main.storyboard;
242 | sourceTree = "";
243 | };
244 | 6145E9AC1BAE61930090DEC0 /* LaunchScreen.storyboard */ = {
245 | isa = PBXVariantGroup;
246 | children = (
247 | 6145E9AD1BAE61930090DEC0 /* Base */,
248 | );
249 | name = LaunchScreen.storyboard;
250 | sourceTree = "";
251 | };
252 | /* End PBXVariantGroup section */
253 |
254 | /* Begin XCBuildConfiguration section */
255 | 6145E9B01BAE61930090DEC0 /* Debug */ = {
256 | isa = XCBuildConfiguration;
257 | buildSettings = {
258 | ALWAYS_SEARCH_USER_PATHS = NO;
259 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
260 | CLANG_CXX_LIBRARY = "libc++";
261 | CLANG_ENABLE_MODULES = YES;
262 | CLANG_ENABLE_OBJC_ARC = YES;
263 | CLANG_WARN_BOOL_CONVERSION = YES;
264 | CLANG_WARN_CONSTANT_CONVERSION = YES;
265 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
266 | CLANG_WARN_EMPTY_BODY = YES;
267 | CLANG_WARN_ENUM_CONVERSION = YES;
268 | CLANG_WARN_INT_CONVERSION = YES;
269 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
270 | CLANG_WARN_UNREACHABLE_CODE = YES;
271 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
272 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
273 | COPY_PHASE_STRIP = NO;
274 | DEBUG_INFORMATION_FORMAT = dwarf;
275 | ENABLE_STRICT_OBJC_MSGSEND = YES;
276 | ENABLE_TESTABILITY = YES;
277 | GCC_C_LANGUAGE_STANDARD = gnu99;
278 | GCC_DYNAMIC_NO_PIC = NO;
279 | GCC_NO_COMMON_BLOCKS = YES;
280 | GCC_OPTIMIZATION_LEVEL = 0;
281 | GCC_PREPROCESSOR_DEFINITIONS = (
282 | "DEBUG=1",
283 | "$(inherited)",
284 | );
285 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
286 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
287 | GCC_WARN_UNDECLARED_SELECTOR = YES;
288 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
289 | GCC_WARN_UNUSED_FUNCTION = YES;
290 | GCC_WARN_UNUSED_VARIABLE = YES;
291 | IPHONEOS_DEPLOYMENT_TARGET = 9.0;
292 | MTL_ENABLE_DEBUG_INFO = YES;
293 | ONLY_ACTIVE_ARCH = YES;
294 | SDKROOT = iphoneos;
295 | TARGETED_DEVICE_FAMILY = "1,2";
296 | };
297 | name = Debug;
298 | };
299 | 6145E9B11BAE61930090DEC0 /* Release */ = {
300 | isa = XCBuildConfiguration;
301 | buildSettings = {
302 | ALWAYS_SEARCH_USER_PATHS = NO;
303 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
304 | CLANG_CXX_LIBRARY = "libc++";
305 | CLANG_ENABLE_MODULES = YES;
306 | CLANG_ENABLE_OBJC_ARC = YES;
307 | CLANG_WARN_BOOL_CONVERSION = YES;
308 | CLANG_WARN_CONSTANT_CONVERSION = YES;
309 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
310 | CLANG_WARN_EMPTY_BODY = YES;
311 | CLANG_WARN_ENUM_CONVERSION = YES;
312 | CLANG_WARN_INT_CONVERSION = YES;
313 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
314 | CLANG_WARN_UNREACHABLE_CODE = YES;
315 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
316 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
317 | COPY_PHASE_STRIP = NO;
318 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
319 | ENABLE_NS_ASSERTIONS = NO;
320 | ENABLE_STRICT_OBJC_MSGSEND = YES;
321 | GCC_C_LANGUAGE_STANDARD = gnu99;
322 | GCC_NO_COMMON_BLOCKS = YES;
323 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
324 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
325 | GCC_WARN_UNDECLARED_SELECTOR = YES;
326 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
327 | GCC_WARN_UNUSED_FUNCTION = YES;
328 | GCC_WARN_UNUSED_VARIABLE = YES;
329 | IPHONEOS_DEPLOYMENT_TARGET = 9.0;
330 | MTL_ENABLE_DEBUG_INFO = NO;
331 | SDKROOT = iphoneos;
332 | TARGETED_DEVICE_FAMILY = "1,2";
333 | VALIDATE_PRODUCT = YES;
334 | };
335 | name = Release;
336 | };
337 | 6145E9B31BAE61930090DEC0 /* Debug */ = {
338 | isa = XCBuildConfiguration;
339 | baseConfigurationReference = 588492C0B1BA299603B92822 /* Pods-NHNetworkTimeExample.debug.xcconfig */;
340 | buildSettings = {
341 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
342 | INFOPLIST_FILE = NHNetworkTimeExample/Info.plist;
343 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
344 | PRODUCT_BUNDLE_IDENTIFIER = com.nch.NHNetworkTimeExample;
345 | PRODUCT_NAME = "$(TARGET_NAME)";
346 | };
347 | name = Debug;
348 | };
349 | 6145E9B41BAE61930090DEC0 /* Release */ = {
350 | isa = XCBuildConfiguration;
351 | baseConfigurationReference = 3F11F492A4C185ACADBF4CD9 /* Pods-NHNetworkTimeExample.release.xcconfig */;
352 | buildSettings = {
353 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
354 | INFOPLIST_FILE = NHNetworkTimeExample/Info.plist;
355 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
356 | PRODUCT_BUNDLE_IDENTIFIER = com.nch.NHNetworkTimeExample;
357 | PRODUCT_NAME = "$(TARGET_NAME)";
358 | };
359 | name = Release;
360 | };
361 | /* End XCBuildConfiguration section */
362 |
363 | /* Begin XCConfigurationList section */
364 | 6145E9961BAE61930090DEC0 /* Build configuration list for PBXProject "NHNetworkTimeExample" */ = {
365 | isa = XCConfigurationList;
366 | buildConfigurations = (
367 | 6145E9B01BAE61930090DEC0 /* Debug */,
368 | 6145E9B11BAE61930090DEC0 /* Release */,
369 | );
370 | defaultConfigurationIsVisible = 0;
371 | defaultConfigurationName = Release;
372 | };
373 | 6145E9B21BAE61930090DEC0 /* Build configuration list for PBXNativeTarget "NHNetworkTimeExample" */ = {
374 | isa = XCConfigurationList;
375 | buildConfigurations = (
376 | 6145E9B31BAE61930090DEC0 /* Debug */,
377 | 6145E9B41BAE61930090DEC0 /* Release */,
378 | );
379 | defaultConfigurationIsVisible = 0;
380 | defaultConfigurationName = Release;
381 | };
382 | /* End XCConfigurationList section */
383 | };
384 | rootObject = 6145E9931BAE61930090DEC0 /* Project object */;
385 | }
386 |
--------------------------------------------------------------------------------
/NHNetworkTime/NHNetAssociation.m:
--------------------------------------------------------------------------------
1 | #import "NHNetAssociation.h"
2 | #import
3 | #import "NHNTLog.h"
4 | #import "NSDate+NetworkClock.h"
5 |
6 | /*┌──────────────────────────────────────────────────────────────────────────────────────────────────┐
7 | │ NTP Timestamp Structure │
8 | │ │
9 | │ 0 1 2 3 │
10 | │ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 │
11 | │ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ │
12 | │ | Seconds | │
13 | │ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ │
14 | │ | Seconds Fraction (0-padded) | <-- 4294967296 = 1 second │
15 | │ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ │
16 | └──────────────────────────────────────────────────────────────────────────────────────────────────┘*/
17 |
18 | #pragma mark - Time converter
19 |
20 | #define JAN_1970 0x83aa7e80 // UNIX epoch in NTP's epoch:
21 | // 1970-1900 (2,208,988,800s)
22 | typedef struct ntpTimestamp {
23 | uint32_t wholeSeconds;
24 | uint32_t fractSeconds;
25 | } NHTimeStamp;
26 |
27 | static NHTimeStamp NTP_1970 = {JAN_1970, 0}; // network time for 1 January 1970, GMT
28 |
29 | static double pollIntervals[18] = {
30 | 2.0, 16.0, 16.0, 16.0, 16.0, 35.0, 72.0, 127.0, 258.0,
31 | 511.0, 1024.0, 2048.0, 4096.0, 8192.0, 16384.0, 32768.0, 65536.0, 131072.0
32 | };
33 |
34 | // Convert from Unix time to NTP time
35 | void unix2ntp(const struct timeval * tv, NHTimeStamp *ntp) {
36 | ntp->wholeSeconds = (uint32_t)(tv->tv_sec + JAN_1970);
37 | ntp->fractSeconds = (uint32_t)(((double)tv->tv_usec + 0.5) * (double)(1LL<<32) * 1.0e-6);
38 | }
39 |
40 | // Convert from NTP time to Unix time
41 | void ntp2unix(const NHTimeStamp *ntp, struct timeval *tv) {
42 | tv->tv_sec = ntp->wholeSeconds - JAN_1970;
43 | tv->tv_usec = (uint32_t)((double)ntp->fractSeconds / (1LL<<32) * 1.0e6);
44 | }
45 |
46 | // get current time in NTP format
47 | void ntp_time_now(NHTimeStamp *ntp) {
48 | struct timeval now;
49 | gettimeofday(&now, (struct timezone *)NULL);
50 | unix2ntp(&now, ntp);
51 | }
52 |
53 | // get (ntpTime2 - ntpTime1) in (double) seconds
54 | double ntpDiffSeconds(NHTimeStamp *start, NHTimeStamp *stop) {
55 | int32_t a;
56 | uint32_t b;
57 | a = stop->wholeSeconds - start->wholeSeconds;
58 | if (stop->fractSeconds >= start->fractSeconds) {
59 | b = stop->fractSeconds - start->fractSeconds;
60 | }
61 | else {
62 | b = start->fractSeconds - stop->fractSeconds;
63 | b = ~b;
64 | a -= 1;
65 | }
66 |
67 | return a + b / 4294967296.0;
68 | }
69 |
70 | @interface NHNetAssociation() {
71 | double fifoQueue[8];
72 |
73 | NHTimeStamp ntpClientSendTime;
74 | NHTimeStamp ntpServerRecvTime;
75 | NHTimeStamp ntpServerSendTime;
76 | NHTimeStamp ntpClientRecvTime;
77 | NHTimeStamp ntpServerBaseTime;
78 | }
79 |
80 | @property GCDAsyncUdpSocket *socket;
81 | @property NSTimer *repeatingTimer; // fires off an ntp request ...
82 | @property int pollingIntervalIndex; // index into polling interval table
83 |
84 | @property int stratum;
85 | @property double timerWobbleFactor; // 0.75 .. 1.25
86 | @property short fifoIndex;
87 |
88 | @property (readonly) double dispersion; // milliSeconds
89 | @property (readonly) double roundtrip; // seconds
90 |
91 | @property (strong, nonatomic) NSMutableArray *observers;
92 |
93 | @end
94 |
95 | @implementation NHNetAssociation
96 |
97 | //Initialize the association with a blank socket and prepare the time transaction to happen every 16 seconds (initial value)
98 |
99 | - (instancetype)initWithServerName:(NSString *) serverName {
100 | if (self = [super init]) {
101 | self.pollingIntervalIndex = 0; // ensure the first timer firing is soon
102 | _active = FALSE; // isn't running till it reports time ...
103 | _trusty = FALSE; // don't trust this clock to start with ...
104 | _offset = INFINITY; // start with net clock meaningless
105 | _server = serverName;
106 |
107 | self.socket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self
108 | delegateQueue:dispatch_queue_create(
109 | [serverName cStringUsingEncoding:NSUTF8StringEncoding], DISPATCH_QUEUE_SERIAL)];
110 |
111 | [self registerObservations];
112 | }
113 |
114 | return self;
115 | }
116 |
117 | - (void)dealloc {
118 | [self unregisterObservations];
119 | }
120 |
121 | - (void)enable {
122 |
123 | // Create a first-in/first-out queue for time samples. As we compute each new time obtained from the server we push it into the fifo. We sample the contents of the fifo for quality and, if it meets our standards we use the contents of the fifo to obtain a weighted average of the times.
124 | for (short i = 0; i < 8; i++) fifoQueue[i] = NAN; // set fifo to all empty
125 | self.fifoIndex = 0;
126 |
127 | // Finally, initialize the repeating timer that queries the server, set it's trigger time to the infinite future, and put it on the run loop .. nothing will happen (yet)
128 | self.repeatingTimer = [NSTimer timerWithTimeInterval:MAXFLOAT
129 | target:self selector:@selector(queryTimeServer)
130 | userInfo:nil repeats:YES];
131 | self.repeatingTimer.tolerance = 1.0; // it can be up to 1 second late
132 | [[NSRunLoop mainRunLoop] addTimer:self.repeatingTimer forMode:NSDefaultRunLoopMode];
133 |
134 | // now start the timer .. fire the first one soon, and put some wobble in its timing so we don't get pulses of activity.
135 | self.timerWobbleFactor = ((float)rand()/(float)RAND_MAX / 2.0) + 0.75; // 0.75 .. 1.25
136 | NSTimeInterval interval = pollIntervals[self.pollingIntervalIndex] * self.timerWobbleFactor;
137 | [self.repeatingTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:interval]];
138 |
139 | self.pollingIntervalIndex = 4; // subsequent timers fire at default intervals
140 | }
141 |
142 | // Set the receiver and send the time query with 2 second timeout, ...
143 | - (void)queryTimeServer {
144 | [self sendTimeQuery];
145 |
146 | // Put some wobble into the repeating time so they don't synchronize and thump the network
147 | self.timerWobbleFactor = ((float)rand()/(float)RAND_MAX / 2.0) + 0.75; // 0.75 .. 1.25
148 | NSTimeInterval interval = pollIntervals[self.pollingIntervalIndex] * self.timerWobbleFactor;
149 | [self.repeatingTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:interval]];
150 | }
151 |
152 | - (void)sendTimeQuery {
153 | NSError * error = nil;
154 |
155 | [self.socket sendData:[self createPacket] toHost:_server port:123 withTimeout:2.0 tag:0];
156 |
157 | if(![self.socket beginReceiving:&error]) {
158 | NTP_Logging(@"Unable to start listening on socket for [%@] due to error [%@]", _server, error);
159 | return;
160 | }
161 | }
162 |
163 | - (void)finish {
164 | [self.repeatingTimer invalidate];
165 |
166 | for (short i = 0; i < 8; i++) fifoQueue[i] = NAN; // set fifo to all empty
167 | self.fifoIndex = 0;
168 |
169 | _active = FALSE;
170 |
171 | if(self.socket) {
172 | [self.socket close];
173 | }
174 | }
175 |
176 | #pragma mark - Network transactions
177 |
178 | /*┌──────────────────────────────────────────────────────────────────────────────────────────────────┐
179 | │ Create a time query packet ... │
180 | │──────────────────────────────────────────────────────────────────────────────────────────────────│
181 | │ │
182 | │ 1 2 3 │
183 | │ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 │
184 | │ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ │
185 | │ [ 0] | L | Ver |Mode | Stratum | Poll | Precision | │
186 | │ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ │
187 | │ [ 1] | Root Delay (32) | in NTP short format │
188 | │ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ │
189 | │ [ 2] | Root Dispersion (32) | in NTP short format │
190 | │ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ │
191 | │ [ 3] | Reference Identifier | │
192 | │ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ │
193 | │ [ 4] | | │
194 | │ | Reference Timestamp (64) | in NTP long format │
195 | │ [ 5] | | │
196 | │ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ │
197 | │ [ 6] | | │
198 | │ | Originate Timestamp (64) | in NTP long format │
199 | │ [ 7] | | │
200 | │ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ │
201 | │ [ 8] | | │
202 | │ | Receive Timestamp (64) | in NTP long format │
203 | │ [ 9] | | │
204 | │ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ │
205 | │ [10] | | │
206 | │ | Transmit Timestamp (64) | in NTP long format │
207 | │ [11] | | │
208 | │ │
209 | └──────────────────────────────────────────────────────────────────────────────────────────────────┘*/
210 |
211 | - (NSData *)createPacket {
212 | uint32_t wireData[12];
213 |
214 | memset(wireData, 0, sizeof wireData);
215 | wireData[0] = htonl((0 << 30) | // no Leap Indicator
216 | (4 << 27) | // NTP v4
217 | (3 << 24) | // mode = client sending
218 | (0 << 16) | // stratum (n/a)
219 | (4 << 8) | // polling rate (16 secs)
220 | (-6 & 0xff)); // precision (~15 mSecs)
221 | wireData[1] = htonl(1<<16);
222 | wireData[2] = htonl(1<<16);
223 |
224 | ntp_time_now(&ntpClientSendTime);
225 |
226 | wireData[10] = htonl(ntpClientSendTime.wholeSeconds); // Transmit Timestamp
227 | wireData[11] = htonl(ntpClientSendTime.fractSeconds);
228 |
229 | return [NSData dataWithBytes:wireData length:48];
230 | }
231 |
232 | - (void)decodePacket:(NSData *) data {
233 | NHNetworkClock *sharedClock = [NHNetworkClock sharedNetworkClock];
234 |
235 | @synchronized(sharedClock) {
236 | // grab the packet arrival time as fast as possible, before computations below ...
237 | ntp_time_now(&ntpClientRecvTime);
238 |
239 | uint32_t wireData[12];
240 | [data getBytes:wireData length:48];
241 |
242 | int mode = ntohl(wireData[0]) >> 24 & 0x07;
243 | self.stratum = ntohl(wireData[0]) >> 16 & 0xff;
244 |
245 | _dispersion = ntohl(wireData[2]) * 0.0152587890625; // error (mS)
246 |
247 | ntpServerBaseTime.wholeSeconds = ntohl(wireData[4]); // when server clock was wound
248 | ntpServerBaseTime.fractSeconds = ntohl(wireData[5]);
249 |
250 | // if the send time in the packet isn't the same as the remembered send time, ditch it ...
251 | if (ntpClientSendTime.wholeSeconds != ntohl(wireData[6]) ||
252 | ntpClientSendTime.fractSeconds != ntohl(wireData[7])) return; // NO;
253 |
254 | ntpServerRecvTime.wholeSeconds = ntohl(wireData[8]);
255 | ntpServerRecvTime.fractSeconds = ntohl(wireData[9]);
256 | ntpServerSendTime.wholeSeconds = ntohl(wireData[10]);
257 | ntpServerSendTime.fractSeconds = ntohl(wireData[11]);
258 |
259 | //determine the quality of this particular time if max_error is less than 50mS (and not zero) AND stratum > 0 AND the mode is 4 (packet came from server) AND the server clock was set less than 1 minute ago
260 | _offset = INFINITY; // clock meaningless
261 | if ((_dispersion < 50.0 && _dispersion > 0.00001) &&
262 | (self.stratum > 0) && (mode == 4) &&
263 | (ntpDiffSeconds(&ntpServerBaseTime, &ntpServerSendTime) < 60.0)) {
264 |
265 | double t41 = ntpDiffSeconds(&ntpClientSendTime, &ntpClientRecvTime); // .. (T4-T1)
266 | double t32 = ntpDiffSeconds(&ntpServerRecvTime, &ntpServerSendTime); // .. (T3-T2)
267 |
268 | _roundtrip = t41 - t32;
269 |
270 | double t21 = ntpDiffSeconds(&ntpServerSendTime, &ntpClientRecvTime); // .. (T2-T1)
271 | double t34 = ntpDiffSeconds(&ntpServerRecvTime, &ntpClientSendTime); // .. (T3-T4)
272 |
273 | _offset = (t21 + t34) / 2.0; // calculate offset
274 |
275 | _active = TRUE;
276 | }
277 |
278 | [self calculateTrusty];
279 |
280 | dispatch_async(dispatch_get_main_queue(), ^{
281 | if(self.delegate && [self.delegate respondsToSelector:@selector(netAssociationDidFinishGetTime:)]) {
282 | [self.delegate netAssociationDidFinishGetTime:self];
283 | }
284 | });
285 | }
286 | }
287 |
288 | - (void)calculateTrusty {
289 | // the packet is trustworthy -- compute and store offset in 8-slot fifo ...
290 |
291 | fifoQueue[self.fifoIndex++ % 8] = _offset; // store offset in seconds
292 | self.fifoIndex %= 8; // rotate index in range
293 |
294 | // look at the (up to eight) offsets in the fifo and and count 'good', 'fail' and 'not used yet'
295 | short good = 0, fail = 0, none = 0;
296 | _offset = 0.0; // reset for averaging
297 |
298 | for (short i = 0; i < 8; i++) {
299 | if (isnan(fifoQueue[i])) { // fifo slot is unused
300 | none++;
301 | continue;
302 | }
303 | if (isinf(fifoQueue[i]) || fabs(fifoQueue[i]) < 0.0001) { // server can't be trusted
304 | fail++;
305 | continue;
306 | }
307 |
308 | good++;
309 | _offset += fifoQueue[i]; // accumulate good times
310 | }
311 |
312 | // if we have at least one 'good' server response or four or more 'fail' responses, we'll inform our management accordingly. If we have less than four 'fails' we won't make any note of that ... we won't condemn a server until we get four 'fail' packets.
313 | double stdDev = 0.0;
314 | if (good > 0 || fail > 3) {
315 | _offset = _offset / good; // average good times
316 |
317 | for (short i = 0; i < 8; i++) {
318 | if (isnan(fifoQueue[i])) continue;
319 |
320 | if (isinf(fifoQueue[i]) || fabs(fifoQueue[i]) < 0.001) continue;
321 |
322 | stdDev += (fifoQueue[i] - _offset) * (fifoQueue[i] - _offset);
323 | }
324 | stdDev = sqrt(stdDev/(float)good);
325 |
326 | _trusty = (good+none > 4) && // four or more 'fails'
327 | (fabs(_offset) > stdDev*3.0); // s.d. < offset
328 |
329 | NTP_Logging(@" [%@] {%3.1f,%3.1f,%3.1f,%3.1f,%3.1f,%3.1f,%3.1f,%3.1f} ↑=%i, ↓=%i, %3.1f(%3.1f) %@", _server,
330 | fifoQueue[0]*1000.0, fifoQueue[1]*1000.0, fifoQueue[2]*1000.0, fifoQueue[3]*1000.0,
331 | fifoQueue[4]*1000.0, fifoQueue[5]*1000.0, fifoQueue[6]*1000.0, fifoQueue[7]*1000.0,
332 | good, fail, _offset*1000.0, stdDev*1000.0, _trusty ? @"↑" : @"↓");
333 |
334 | }
335 |
336 | // if the association is providing times which don't vary much, we could increase its polling interval. In practice, once things settle down, the standard deviation on any time server seems to fall in the 70-120mS range (plenty close for our work). We usually pick up a few stratum=1 servers, it would be a Good Thing to not hammer those so hard ...
337 | if ((self.stratum == 1 && self.pollingIntervalIndex != 6) ||
338 | (self.stratum == 2 && self.pollingIntervalIndex != 5)) {
339 | self.pollingIntervalIndex = 7 - self.stratum;
340 | }
341 | }
342 |
343 | #pragma mark - Network callbacks
344 |
345 | - (void)udpSocket:(GCDAsyncUdpSocket *)sock didConnectToAddress:(NSData *)address {
346 | NTP_Logging(@"didConnectToAddress");
347 | }
348 |
349 | - (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotConnect:(NSError *)error {
350 | NTP_Logging(@"didNotConnect - %@", error.description);
351 | }
352 |
353 | - (void)udpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag {
354 | }
355 |
356 | - (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error {
357 | NTP_Logging(@"didNotSendDataWithTag - %@", error.description);
358 | }
359 |
360 | - (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
361 | fromAddress:(NSData *)address withFilterContext:(id)filterContext {
362 | [self decodePacket:data];
363 | }
364 |
365 | - (void)udpSocketDidClose:(GCDAsyncUdpSocket *)sock withError:(NSError *)error {
366 | NTP_Logging(@"Socket closed : [%@]", _server);
367 | }
368 |
369 | // Make an NSDate from ntpTimestamp ... (via seconds from JAN_1970) ...
370 | - (NSDate *) dateFromNetworkTime:(struct ntpTimestamp *) networkTime {
371 | return [NSDate dateWithTimeIntervalSince1970:ntpDiffSeconds(&NTP_1970, networkTime)];
372 | }
373 |
374 | #pragma mark - Pretty printer
375 |
376 | - (NSString *)prettyPrintTimers {
377 | NSMutableString * prettyString = [NSMutableString stringWithFormat:@"prettyPrintTimers\n\n"];
378 |
379 | [prettyString appendFormat:@"time server addr: [%@]\n"
380 | " round trip time: %7.3f (mS)\n"
381 | " clock offset: %7.3f (mS)\n\n",
382 | _server, _roundtrip * 1000.0, _offset * 1000.0];
383 |
384 | return prettyString;
385 | }
386 |
387 | - (NSString *)description {
388 | return [NSString stringWithFormat:@"%@ [%@] stratum=%i; offset=%3.1f±%3.1fmS",
389 | _trusty ? @"↑" : @"↓", _server, self.stratum, _offset, _dispersion];
390 | }
391 |
392 | #pragma mark - Notification Traps
393 |
394 | - (void)registerObservations {
395 |
396 | // if associations are going to have a life, they have to react to their app being backgrounded.
397 |
398 | __weak typeof(self) weakSelf = self;
399 |
400 | if(self.observers && self.observers.count > 0) {
401 | [self unregisterObservations];
402 | } else {
403 | self.observers = [[NSMutableArray alloc] init];
404 | }
405 |
406 | [self.observers addObject:[[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidEnterBackgroundNotification
407 | object:nil
408 | queue:nil
409 | usingBlock:^
410 | (NSNotification * note) {
411 | NTP_Logging(@"Application -> Background");
412 |
413 | __strong typeof(weakSelf) strongSelf = weakSelf;
414 |
415 | if(strongSelf) {
416 | [strongSelf finish];
417 | }
418 | }]];
419 |
420 | [self.observers addObject:[[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationWillEnterForegroundNotification
421 | object:nil
422 | queue:nil
423 | usingBlock:^
424 | (NSNotification * note) {
425 | NTP_Logging(@"Application -> Foreground");
426 |
427 | __strong typeof(weakSelf) strongSelf = weakSelf;
428 |
429 | if(strongSelf) {
430 | [strongSelf enable];
431 | }
432 | }]];
433 |
434 | // significantTimeChange -- trash the fifo ..
435 | [self.observers addObject:[[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationSignificantTimeChangeNotification
436 | object:nil
437 | queue:nil
438 | usingBlock:^
439 | (NSNotification * note) {
440 | NTP_Logging(@"Application -> SignificantTimeChange");
441 |
442 | __strong typeof(weakSelf) strongSelf = weakSelf;
443 |
444 | if(strongSelf) {
445 | for (short i = 0; i < 8; i++) strongSelf->fifoQueue[i] = NAN; // set fifo to all empty
446 | strongSelf.fifoIndex = 0;
447 | }
448 | }]];
449 | }
450 |
451 | - (void)unregisterObservations {
452 | if(self.observers) {
453 | for(id observer in self.observers) {
454 | [[NSNotificationCenter defaultCenter] removeObserver:observer];
455 | }
456 |
457 | [self.observers removeAllObjects];
458 | }
459 | }
460 |
461 | @end
462 |
--------------------------------------------------------------------------------