Giter Club home page Giter Club logo

nhnetworktime's Introduction

NHNetworkTime

A network time protocol (NTP) client.

About

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.

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.

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.

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.

Compatible

  • iOS 7 and later.
  • Objective C, and Swift with bridge header (read below guide)

Usage

Cocoapod

Add below line to Podfile:

pod NHNetworkTime

and then run below command in Terminal to install:
pod install

Note: If above pod isn't working, try using below pod defination in Podfile:
pod 'NHNetworkTime', :git => 'https://github.com/huynguyencong/NHNetworkTime.git'

Manual

Add all file in folder NHNetworkTime to your project. Then add CocoaAsyncSocket use Cocoapod or add manual.

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];

Swift

#####Use use_frameworks!

If you have use_frameworks! option in Podfile, import NHNetworkTime framework in each code file use NHNetworkTime objects:

@import NHNetworkTime
Not use use_frameworks!

Import NHNetworkTime.h to your in bridge header file:

#import <NHNetworkTime.h>
In your code

Now, you can call below code in your code:

NHNetworkClock.sharedNetworkClock().synchronize()

and:

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("syncCompleteNotification"), name: kNHNetworkTimeSyncCompleteNotification, object: nil)

More from NHNetworkClock

  • Use NSNotifcationCenter to add observer kNHNetworkTimeSyncCompleteNotification to receive notification when time sync complete
  • Property isSynchronized: Check network time synchronized or not
  • Property shouldUseSavedSynchronizedTime: Should use offset time saved in the last synchronization before sync from server. Default is YES.
  • Property isAutoSynchronizedWhenUserChangeLocalTime: Is auto sync when user change local time. Default is YES.

Custom time server

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:

asia.pool.ntp.org
europe.pool.ntp.org
north-america.pool.ntp.org

About this source

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:

  • Post notification when sync complete
  • Property make you know whether sync complete or not
  • Save offset time local to use immediately right after launch app, don't have to waiting for server
  • Auto sync when user change local time

License

NHNetworkTime is released under the Apache license. See LICENSE for details. Copyright © Nguyen Cong Huy

nhnetworktime's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nhnetworktime's Issues

Version conflict in POD

As NHNetworkTime uses CocoaAsyncSocket (<= 7.4.1) and the other library which i'm using uses CocoaAsyncSocket (~> 7.4.3), I am not able to integrate successfully NHNetworkTime. How could i solve it?

Did not update correct time after app is moved from background to foreground

When app is moving to the background, UIApplicationDidEnterBackgroundNotification is observed and every NHNetAssociation execute [self finish], whitch execte [self unregisterObservations], which remove all observers, including UIApplicationWillEnterForegroundNotification.

So, after app is on foreground, there is no observers to make [self enable] for NHNetAssociation's objects.

Workaround - execte [[NHNetworkClock sharedNetworkClock] synchronize] in applicationDidBecomeActive:, not in didFinishLaunchingWithOptions: method of appDelegate.

Pointer being freed was not allocated crash during -[NHNetworkClock createAssociations]

iOS 10.0.1 (14A403)
iPad Pro (9.7 inch) - Real device
Debug build (attached Build & Run)

CocoaPods
Using NHNetworkTime (1.7)
Using CocoaAsyncSocket (7.5.0)

in [NHNetworkClock createAssociations]

screen shot 2016-09-28 at 2 16 03 pm

***(2209,0x16e19b000) malloc: *** error for object 0x151e373f0: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
(lldb) po self.timeAssociations
<__NSArrayM 0x17004bc70>(
↓ [208.53.158.34] stratum=0; offset=inf±0.0mS,
↓ [208.53.158.34] stratum=0; offset=inf±0.0mS,
↓ [193.164.133.53] stratum=0; offset=inf±0.0mS,
↓ [193.164.133.53] stratum=0; offset=inf±0.0mS,
↓ [41.73.42.22] stratum=0; offset=inf±0.0mS,
↓ [41.73.42.22] stratum=0; offset=inf±0.0mS,
↓ [196.10.55.57] stratum=0; offset=inf±0.0mS,
↓ [196.10.55.57] stratum=0; offset=inf±0.0mS,
↓ [203.19.252.4] stratum=0; offset=inf±0.0mS,
↓ [203.19.252.4] stratum=0; offset=inf±0.0mS,
↓ [108.61.73.244] stratum=0; offset=inf±0.0mS,
↓ [108.61.73.244] stratum=0; offset=inf±0.0mS,
↓ [146.231.129.81] stratum=0; offset=inf±0.0mS,
↓ [146.231.129.81] stratum=0; offset=inf±0.0mS,
↓ [192.146.137.13] stratum=0; offset=inf±0.0mS,
↓ [192.146.137.13] stratum=0; offset=inf±0.0mS,
↓ [188.114.116.1] stratum=0; offset=inf±0.0mS,
↓ [188.114.116.1] stratum=0; offset=inf±0.0mS,
↓ [176.221.42.125] stratum=0; offset=inf±0.0mS,
↓ [176.221.42.125] stratum=0; offset=inf±0.0mS,
↓ [23.239.26.89] stratum=0; offset=inf±0.0mS,
↓ [23.239.26.89] stratum=0; offset=inf±0.0mS,
↓ [77.72.179.17] stratum=0; offset=inf±0.0mS,
↓ [77.72.179.17] stratum=0; offset=inf±0.0mS,
↓ [74.120.8.2] stratum=0; offset=inf±0.0mS,
↓ [74.120.8.2] stratum=0; offset=inf±0.0mS,
↓ [148.167.132.201] stratum=0; offset=inf±0.0mS,
↓ [148.167.132.201] stratum=0; offset=inf±0.0mS,
↓ [204.2.134.163] stratum=0; offset=inf±0.0mS,
↓ [204.2.134.163] stratum=0; offset=inf±0.0mS,
↓ [103.242.68.69] stratum=0; offset=inf±0.0mS,
↓ [103.242.68.69] stratum=0; offset=inf±0.0mS,
↓ [157.7.154.23] stratum=0; offset=inf±0.0mS,
↓ [157.7.154.23] stratum=0; offset=inf±0.0mS,
↓ [128.138.141.172] stratum=0; offset=inf±0.0mS,
↓ [128.138.141.172] stratum=0; offset=inf±0.0mS,
↓ [193.219.61.120] stratum=0; offset=inf±0.0mS,
↓ [193.219.61.120] stratum=0; offset=inf±0.0mS,
↓ [82.219.4.31] stratum=0; offset=inf±0.0mS,
↓ [82.219.4.31] stratum=0; offset=inf±0.0mS,
↓ [196.10.54.57] stratum=0; offset=inf±0.0mS,
↓ [196.10.54.57] stratum=0; offset=inf±0.0mS,
↓ [82.200.209.236] stratum=0; offset=inf±0.0mS,
↓ [186.33.229.233] stratum=0; offset=inf±0.0mS,
↓ [54.232.82.232] stratum=0; offset=inf±0.0mS,
↓ [210.23.18.200] stratum=0; offset=inf±0.0mS,
↓ [201.217.3.86] stratum=0; offset=inf±0.0mS,
↓ [94.125.129.7] stratum=0; offset=inf±0.0mS,
↓ [74.123.30.8] stratum=0; offset=inf±0.0mS,
↓ [54.252.165.245] stratum=0; offset=inf±0.0mS,
↓ [104.236.167.15] stratum=0; offset=inf±0.0mS
)


(lldb) po timeAssociation
↓ [82.200.209.236] stratum=0; offset=inf±0.0mS

if internet is off and time changed

I have done an experiment. I have turned off the internet and changed the time. Will NHNetworkTime still gives accurate time? In my case, it did not return the true time. How still i could achieve the true time if internet is off

Crash with error "EXC_BAD_ACCESS"

Crashed: com.apple.main-thread
EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x0000000000000001
Crashed: com.apple.main-thread
0 libobjc.A.dylib 0x183d00908 objc_msgSend + 8
1 NHNetworkTime 0x105ef3eec -[NHNetworkClock finishAssociations] + 244
2 NHNetworkTime 0x105ef3334 -[NHNetworkClock reset] + 48
3 NHNetworkTime 0x105ef3fc8 -[NHNetworkClock synchronize] + 32
4 Foundation 0x1854961bc -[__NSObserver _doit:] + 312
5 CoreFoundation 0x184ac4c3c CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER + 20
6 CoreFoundation 0x184ac41b8 _CFXRegistrationPost + 428
7 CoreFoundation 0x184ac3f14 ___CFXNotificationPost_block_invoke + 216
8 CoreFoundation 0x184b4184c -[_CFXNotificationRegistrar find:object:observer:enumerator:] + 1408
9 CoreFoundation 0x1849faf38 _CFXNotificationPost + 384
10 Foundation 0x18546bbbc -[NSNotificationCenter postNotificationName:object:userInfo:] + 68
11 UIKit 0x18eb2d238 -[UIApplication significantTimeChange] + 120
12 CoreFoundation 0x184ac4c3c CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER + 20
13 CoreFoundation 0x184ac4b80 ___CFXRegistrationPost_block_invoke + 64
14 CoreFoundation 0x184adb2bc CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK + 20
15 CoreFoundation 0x184adaa7c __CFRunLoopDoBlocks + 264
16 CoreFoundation 0x184ad8abc __CFRunLoopRun + 2004
17 CoreFoundation 0x1849f8da8 CFRunLoopRunSpecific + 552
18 GraphicsServices 0x1869de020 GSEventRunModal + 100
19 UIKit 0x18ea18758 UIApplicationMain + 236
20 GearManager 0x1045405f0 main (main.m:26)
21 libdyld.dylib 0x184489fc0 start + 4

Issue in pure Swift project with Cocoapods 1.0.0

When use use_frameworks! in a pure Swift project with Cocoapods 1.0.0, there is an issue:

/Users/xxx/Library/Developer/Xcode/DerivedData/xxx/Build/Products/Debug-iphoneos/NHNetworkTime/NHNetworkTime.framework/Headers/NHNetAssociation.h:16:9: error: 'CocoaAsyncSocket/GCDAsyncUdpSocket.h' file not found

"NHNetworkTime.h file not found"

After installing cocoapods by adding pod 'NHNetworkTime', :git => 'https://github.com/huynguyencong/NHNetworkTime.git' to my podfile and adding #import "NHNetworkTime.h" to my bridging header i consistently get error "NHNetworkTime.h file not found". I tried using pod 'NHNetworkTime in my podfile instead but it still didn't work. I have tried with AND without use_frameworks! and same result each time. Any advice?

Need to add a Privacy Manifest for use of NSUserDefaults

Apple is going to start requiring Privacy Manifests sometime in “Spring 2024” for apps and 3rd Party SDKs. Failure to comply with their mandate may lead to issues with releasing new versions of your app on the Apple App Store. Here is the WWDC 2023 video describing Privacy Manifests if you would like more context on Privacy Manifests.

Our app uses NHNetworkTime library and we have found a usage of NSUserDefaults that falls under the required Reasons API category in Privacy Manifests.

https://github.com/huynguyencong/NHNetworkTime/blob/master/NHNetworkTime/NHNetworkClock.m#L94

As we want to continue using this SDK, we would like to request an .xcprivacy added to the library annotating the usage of NSUserDefaults. This will help unblocks apps that use this SDK and comply with the Privacy Manifest requirements from Apple.

Using NHNetworkTime for Cocoa application

Hi there—I'm looking to use NHNetworkTime for a macOS application. Other than removing references to UIKit, do you have any other suggestions for my conversion? I replaced the UIApplicationSignificantTimeChangeNotification with NSSystemClockDidChangeNotification and commented out similarly replaced the foreground/background notifications.

Support for SwiftPM

Thanks for such a useful project. Any chance you could add support for Swift PM?

Time is not synchronised if we call synchronize multiple times

when we call [[NHNetworkClock sharedNetworkClock]synchronize]; multiple times ( some 4 times )

[NSDate networkDate] will always return the local time (time is not synchronised) and in the console we are getting the following error

dnssd_clientstub deliver_request: socketpair failed 24 (Too many open files)

pod is not found

add pod 'NHNetworkTime'

then after executing command 'pod install', it fails

[!] Unable to find a specification for NHNetworkTime

Time sync completion block never get called

Hello, I clone the project and test it on my iphone6. I found that the sync block never get called thus the text label always shows "Time is not synchronized",and both time babe shows the wrong local time. I ping the ntp server seems the network is fine. Any idea why this happened? Thanks.

Why syncWithCompleteBlock not recommended?

In your readME you state that it is better to use an observer to makes updates when sync is completed. You recommend not to use the syncWithComplete block for this. What is the reason that it is not recommended?

NSOperationQueue

I have some issues when multiple times syncWithCompletion is called. Some time nothing happens.
So i start looking around your code.
Every time someone is calling syncWithCompletion your are allocating a new NSOperationQueue.
At your reset it will be wise to cancel the scheduled operations that you are adding.
I suggest a strong reference for OperationQueue and every time someone is calling a sync to cancel all schedule operations.
Make sense?

Got crash issue from fabric.

Platform: ios
Issue #: 1061
Issue ID: 5ba553daf8b88c2963c7df84
Session ID: 68ceead1616b476fb390e1b15bdce378_DNE_0_v2
Date: 2018-09-28T14:44:00Z
OS Version: 11.4.1 (15G77)
Device: iPhone 6s
RAM Free: 4.7%
Disk Free: 41.1%

Crashed: NSOperationQueue 0x1c1024040 (QOS: UNSPECIFIED)
0 libsystem_platform.dylib 0x18159aa80 _platform_memmove + 176
1 CoreFoundation 0x18184ac3c -[__NSArrayM insertObject:atIndex:] + 356
2 CoreFoundation 0x18184ac3c -[_NSArrayM insertObject:atIndex:] + 356
3 NHNetworkTime 0x104463d54 -[NHNetworkClock createAssociations] + 1340
4 CoreFoundation 0x181986580 invoking
+ 144
5 CoreFoundation 0x181865748 -[NSInvocation invoke] + 284
6 Foundation 0x1823a7308 -[NSInvocationOperation main] + 40
7 Foundation 0x1822e7cac -[__NSOperationInternal _start:] + 848
8 Foundation 0x1823a876c __NSOQSchedule_f + 404
9 libdispatch.dylib 0x181270a60 _dispatch_client_callout + 16
10 libdispatch.dylib 0x181278e94 _dispatch_continuation_pop$VARIANT$mp + 424
11 libdispatch.dylib 0x1812777cc _dispatch_async_redirect_invoke$VARIANT$mp + 604
12 libdispatch.dylib 0x18127dcac _dispatch_root_queue_drain + 588
13 libdispatch.dylib 0x18127d9fc _dispatch_worker_thread3 + 120
14 libsystem_pthread.dylib 0x1815a3fac _pthread_wqthread + 1176
15 libsystem_pthread.dylib 0x1815a3b08 start_wqthread + 4

timeAssociations is NSMutableArray, should be copied or make atomic.

timeAssociations is NSMutableArray, should be copied or make atomic.
Otherwise will cause :
*** Collection <__NSArrayM: 0x157813f20> was mutated while being enumerated.

Thread : Fatal Exception: NSGenericException
0 CoreFoundation 0x184655900 __exceptionPreprocess
1 libobjc.A.dylib 0x183cc3f80 objc_exception_throw
2 CoreFoundation 0x184655334 -[NSException name]
3 Musical.ly 0x1010801d8 -NHNetworkClock finishAssociations
4 Musical.ly 0x10107f270 -NHNetworkClock reset
5 Musical.ly 0x10108034c -NHNetworkClock syncWithComplete:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle </var/containers/Bundle/Application/443F9124-BDDA-452E-A0E3-E73C81930BC0/timeTesting.app> (loaded)' with name 'Rkk-g4-vge-view-TV7-kw-gIS' and directory 'Main.storyboardc''

I'm getting an error while using NHNetworkTime

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle </var/containers/Bundle/Application/443F9124-BDDA-452E-A0E3-E73C81930BC0/timeTesting.app> (loaded)' with name 'Rkk-g4-vge-view-TV7-kw-gIS' and directory 'Main.storyboardc''

May i know what am I doing wrong?

My question is How can i refresh the time inside the viewController, if the time has not be loaded after the timeout?

Sometimes I get Critical failure: the LastResort font is unavailable.

: CGContextSetFillColorWithColor: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.

Got crash issue from Fabric.

Platform: ios
Bundle Identifier:
Issue #: 980
Issue ID: 5b859cb16007d59fcd1352c2
Session ID: 88f95cab8b4c4d3da433ccfb2a5ddb41_DNE_0_v2
Date: 2018-10-09T10:33:00Z
OS Version: 12.0.0 (16A366)
Device: iPhone 6
RAM Free: 1.5%
Disk Free: 41.3%

#0. Crashed: com.apple.main-thread
0 libobjc.A.dylib 0x182f84d68 objc_msgSend + 8
1 NHNetworkTime 0x1025afeec -[NHNetworkClock finishAssociations] + 244
2 NHNetworkTime 0x1025af334 -[NHNetworkClock reset] + 48
3 NHNetworkTime 0x1025affc8 -[NHNetworkClock synchronize] + 32
4 Foundation 0x184744fdc -[__NSObserver _doit:] + 316
5 CoreFoundation 0x183d0cd14

File Descriptor leaks

  1. Put this code [[NHNetworkClock sharedNetworkClock] synchronize];
    into applicationDidBecomeActive
  2. print used File Descriptors using lsof function from the following stackoverflow post http://stackoverflow.com/a/8153026
  3. Use lsof in applicationDidBecomeActive and applicationWillResignActive
  4. Make app active/inactive 10+ times.
    Result: File Descriptors amount will grow up like crazy. Finally you will get 'Too many open files' error and app will not work correctly or crash.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.