Elegant NTP date library in Swift

Related tags

Networking lyft
Overview

Kronos is an NTP client library written in Swift. It supports sub-seconds precision and provides a stable monotonic clock that won't be affected by changes in the clock.

Example app

This is an example app that displays the monotonic Clock.now on the left and the system clock (initially out of date) on the right.

ascii-clock

Usage

Sync clock using a pool of NTP servers

Calling Clock.sync will fire a bunch of NTP requests to up to 5 of the servers on the given NTP pool (default is time.apple.com). As soon as we get the first response, the given closure is called but the Clock will keep trying to get a more accurate response.

Clock.sync { date, offset in
    // This is the first sync (note that this is the fastest but not the
    // most accurate run
    print(date)
}

Get an NTP sync'ed date

Clock.now is a monotonic NSDate that won't be affected by clock changes.

NSTimer.scheduledTimerWithTimeInterval(1.0, target: self,
                                       selector: #selector(Example.tick),
                                       userInfo: nil, repeats: true)

@objc func tick() {
    print(Clock.now) // Note that this clock will get more accurate as
                     // more NTP servers respond.
}

Installation

Embedded frameworks require a minimum deployment target of iOS 8 or OS X Mavericks (10.9).

CocoaPods

CocoaPods is a dependency manager for Cocoa projects. You can install it with the following command:

$ gem install cocoapods

CocoaPods 0.39.0+ is required to build Kronos.

To integrate Kronos into your Xcode project using CocoaPods, specify it in your Podfile:

platform :ios, '8.0'
use_frameworks!

pod 'Kronos'

Then, run the following command:

$ pod install

Swift package manager (experimental)

Swift PM is a tool for managing distribution of source code.

To integrate Kronos into your project using Swift PM use:

$ export SWIFT_EXEC=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc
$ swift build

Carthage

Carthage is a decentralized dependency manager for Cocoa. You can install it by following the instructions here.

To integrate Kronos into your project using Carthage, specify it in your Cartfile:

github "MobileNativeFoundation/Kronos"

Then, run the following command:

$ carthage update

Looking for Kronos for your Android application? Check out Kronos for Android

Comments
  • adjust TimeFreeze on reboot rather than dropping it

    adjust TimeFreeze on reboot rather than dropping it

    Good can be better then None. We'd rather have the best guess at the correct time rather than no time at all, so rather than dropping a persisted TimeFreeze on reboot, assume the current device time is consistent with the previous device time.

    opened by craffert0 12
  • Don't bind sockaddr into sockaddr_storage unsafely

    Don't bind sockaddr into sockaddr_storage unsafely

    By binding sockaddr into a sockaddr_storage we are actually assigning random memory bytes into the sockaddr_storage structre since sockaddr_t is actually smaller than sockaddr_storage.

    opened by Reflejo 11
  • Expose current NTP time along with associated analytical metadata

    Expose current NTP time along with associated analytical metadata

    Time since last NTP sync can be a good indicator of the "fresh"-ness of a vended NTP time.

    Does not replace existing APIs; callers can continue to get the timestamp as a TimeInterval directly rather than a struct that wraps it.

    opened by ryanrhee 11
  • Binary distribution plans?

    Binary distribution plans?

    hi everyone πŸ‘‹

    we are using Kronos as a dependency in Datadog iOS SDK and we were wondering if you had any plans for distributing Kronos as binary / xcframework?

    opened by buranmert 6
  • Removal: VALID_ARCHS

    Removal: VALID_ARCHS

    Apple Silicon machines have arm64 simulators Previous configuration wasn't building for these machines Now we let the compiler decide on VALID_ARCHS by default

    If specifying VALID_ARCHS in xcconfig was done out of neccessity somehow, we can add arm64 to them instead of removing.

    opened by buranmert 6
  • App Restarts and Network unavailable

    App Restarts and Network unavailable

    @Reflejo

    How does this behave when a network is not present, is slow or fails to complete request or user restarts app with no network.

    Does clock.now go out of sync and become unreliable?

    opened by otymartin 6
  • Crash in NTPPacket.swift

    Crash in NTPPacket.swift

    I am getting crash reports from NTPPacket, not a lot since there are thousand of users, but 10 in the last two weeks. Sometimes the user has been running the app for an hour without problems. It is also weird that the log points to line 20, which is empty (but that could be an error in the reporting).

    MAIN THREAD - CRASHED CoreFoundation CFAssertMismatchedTypeID CoreFoundation CFRunLoopSourceInvalidate CFNetwork CFNetServiceBrowserStopSearch CoreFoundation CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION CoreFoundation __CFRunLoopDoSource0 CoreFoundation __CFRunLoopDoSources0 SprintTimer main NTPPacket.swift:20 libdyld.dylib start

    opened by jarlabanke 5
  • Kronos not working on cellular data but only on Wifi?

    Kronos not working on cellular data but only on Wifi?

    It looks like Clock.sync() does not work if I have WiFi off and cellular data (LTE) on. In particular, the "first:" and "completion:" blocks never get called. It works if WiFi is on. Am I missing something? It seems rather odd.

    opened by agforte 5
  • Don't restore from storage after reboot

    Don't restore from storage after reboot

    If the device clock changes after reboot before Kronos is updated, the "trusted" time will be wrong since we'll apply the offset to the wrong ground time. This breaks the "trusted" guarantee.

    opened by Reflejo 5
  • Authorisation asked for local network on iOS 14 on cellular network

    Authorisation asked for local network on iOS 14 on cellular network

    Hello,

    if the lib is inclued in an app running on iOS 14 an authorisation is asked at launch in a system popup :

    "NAME_OF_YOUR_APP" would like to find and connect to devices on your local network. This app will be able to discover and connect to devices on the networks you use. Don't allow - OK

    This does not appear on Wi-Fi, it is displayed only if the phone is on cellular network like 4G.

    This is triggered by Clock.sync()

    Why Kronos wants to use local network ? How to avoid this popup in any case ?

    Thanks

    opened by ben-j69 4
  • BUILD_LIBRARY_FOR_DISTRIBUTION set to YES

    BUILD_LIBRARY_FOR_DISTRIBUTION set to YES

    Origin issue: #81

    Preparation step for binary distribution.

    If we build Kronos with BUILD_LIBRARY_FOR_DISTRIBUTION = YES and add the output xcframework file as an asset to releases then our users can use this binary in most of the cases (old Xcode versions will still need to fallback to building from source but that's okay i guess). Does this make sense? Do you think we need to make other changes as well?

    Also, you will need to add this to your release process; is this okay with you? (I'd be happy to help but this step requires admin rights i guess)

    opened by buranmert 4
  • Synced Clock for AR Session

    Synced Clock for AR Session

    Hello everyone,

    I would like to build an app that records frames and depth images throughout an AR session. For this purpose I need to have the time synchronized as best as possible.

    My question is, whether there is a better way to get the ARFrame timestamps synced than to call sync before recording and safe the offset to add it later to the recorded internal timestamps.

    Thanks already for your help!

    opened by xlDownxl 0
  • Add IPv4 preference support

    Add IPv4 preference support

    In our tests with Austrian time servers we often see that using IPv6 addresses results in much slower query times (consistently 10 seconds instead of ~4 with only IPv4).

    This PR adds a new parameter to the Clock.sync call and NTPClient to allow the preference of IPv4 addresses if both IPv4 and IPv6 addresses are resolved.

    opened by martinreichart 1
  • Data race in static Kronos.Clock.annotatedNow.getter

    Data race in static Kronos.Clock.annotatedNow.getter

    Screenshot 2021-04-19 at 18 57 52 Screenshot 2021-04-19 at 19 01 41
    WARNING: ThreadSanitizer: data race (pid=97366)
      Read of size 8 at 0x0001164e9888 by thread T4:
        #0 static Clock.annotatedNow.getter <null>:2 (Kronos:x86_64+0x26a76ca)
        #1 static Clock.now.getter <null>:2 (Kronos:x86_64+0x26a747d)
    
      Previous write of size 8 at 0x0001164e9888 by main thread:
        #0 static Clock.stableTime.setter <null>:2 (Kronos:x86_64+0x26a6dcf)
        #1 closure #1 in static Clock.sync(from:samples:first:completion:) <null>:2 (Kronos:x86_64+0x26a827e)
        #2 partial apply for closure #1 in static Clock.sync(from:samples:first:completion:) <null>:2 (Kronos:x86_64+0x26a86b5)
        #3 $defer #1 () in closure #1 in closure #1 in NTPClient.query(pool:version:port:numberOfSamples:maximumServers:timeout:progress:) <null>:2 (Kronos:x86_64+0x26b7cf7)
        #4 closure #1 in closure #1 in NTPClient.query(pool:version:port:numberOfSamples:maximumServers:timeout:progress:) <null>:2 (Kronos:x86_64+0x26b783c)
        #5 partial apply for closure #1 in closure #1 in NTPClient.query(pool:version:port:numberOfSamples:maximumServers:timeout:progress:) <null>:2 (Kronos:x86_64+0x26bd6f8)
        #6 closure #1 in NTPClient.query(ip:port:version:timeout:numberOfSamples:completion:) <null>:2 (Kronos:x86_64+0x26b9af7)
        #7 partial apply for closure #1 in NTPClient.query(ip:port:version:timeout:numberOfSamples:completion:) <null>:2 (Kronos:x86_64+0x26bdb8e)
        #8 thunk for @escaping @callee_guaranteed (@guaranteed Data?, @unowned Double) -> () <null>:2 (Kronos:x86_64+0x26ba39d)
        #9 closure #1 in NTPClient.sendAsyncUDPQuery(to:port:timeout:completion:) <null>:2 (Kronos:x86_64+0x26bd0dd)
        #10 @objc closure #1 in NTPClient.sendAsyncUDPQuery(to:port:timeout:completion:) <null>:2 (Kronos:x86_64+0x26bd1f3)
        #11 __CFSocketPerformV0 <null>:2 (CoreFoundation:x86_64+0x92fd9)
        #12 start <null>:2 (libdyld.dylib:x86_64+0x1408)
    
      Location is global 'static Clock.stableTime' at 0x0001164e9888 (Kronos+0x000005b96888)
    
      Thread T4 (tid=1302869, running) is a GCD worker thread
    
    opened by Usipov 2
Releases(4.2.1)
Owner
Mobile Native Foundation
Mobile Native Foundation
Elegant network abstraction layer in Swift.

Elegant network abstraction layer in Swift. δΈ­ζ–‡ Design Features Requirements Communication Installation Usage Base Usage - Target - Request - Download

null 100 Dec 9, 2022
Elegant API Abstraction for Swift

Endpoint (Deprecated) ⚠️ This project has been deprecated. Consider using Moya and MoyaSugar instead. ?? Elegant API Abstraction for Swift. At a Glanc

Suyeol Jeon 35 Mar 29, 2019
An elegant yet powerful iOS networking layer inspired by ActiveRecord.

Written in Swift 5 AlamoRecord is a powerful yet simple framework that eliminates the often complex networking layer that exists between your networki

Tunespeak 19 Nov 19, 2022
SwiftCANLib is a library used to process Controller Area Network (CAN) frames utilizing the Linux kernel open source library SOCKETCAN.

SwiftCANLib SwiftCANLib is a library used to process Controller Area Network (CAN) frames utilizing the Linux kernel open source library SOCKETCAN. Th

Tim Wise 4 Oct 25, 2021
Easy to use OAuth 2 library for iOS, written in Swift.

Heimdallr Heimdallr is an OAuth 2.0 client specifically designed for easy usage. It currently supports the resource owner password credentials grant f

trivago N.V. 628 Oct 17, 2022
Swift based OAuth library for iOS

OAuthSwift Swift based OAuth library for iOS and macOS. Support OAuth1.0, OAuth2.0 Twitter, Flickr, Github, Instagram, Foursquare, Fitbit, Withings, L

OAuthSwift 3.1k Jan 6, 2023
πŸ‡ A Swift HTTP / HTTPS networking library just incidentally execute on machines

Thus, programs must be written for people to read, and only incidentally for machines to execute. Harold Abelson, "Structure and Interpretation of Com

John Lui 845 Oct 30, 2022
Lightweight library for web server applications in Swift on macOS and Linux powered by coroutines.

Why Zewo? β€’ Support β€’ Community β€’ Contributing Zewo Zewo is a lightweight library for web applications in Swift. What sets Zewo apart? Zewo is not a w

Zewo 1.9k Dec 22, 2022
A lightweight library for writing HTTP web servers with Swift

Taylor Disclaimer: Not actively working on it anymore. You can check out some alternatives Swift 2.0 required. Working with Xcode 7.1. Disclaimer: It

Jorge Izquierdo 925 Nov 17, 2022
Super lightweight async HTTP server library in pure Swift runs in iOS / MacOS / Linux

Embassy Super lightweight async HTTP server in pure Swift. Please read: Embedded web server for iOS UI testing. See also: Our lightweight web framewor

Envoy 540 Dec 15, 2022
An Generic HTTP Request Library For Swift

GRequest An HTTP request library written in Swift. ##Basic Usage Be simple, as it should be: Request("https://api.github.com/repos/lingoer/SwiftyJSON/

Ruoyu Fu 114 Oct 18, 2022
Lightweight REST and JSON library for Swift.

RestEssentials is an extremely lightweight REST and JSON library for Swift and can be used on iOS, iPadOS, macOS, tvOS, and watchOS. Features Easily p

null 37 Nov 2, 2022
File downloading library for Swift 3

VeloxDownloader About: VeloxDownloader is an easy to use,elegant, native yet powerfull download library made with Swift 3. It abstracts all the comple

Nitin Sharma 20 Apr 24, 2019
WebSocket(RFC-6455) library written using Swift

DNWebSocket Object-Oriented, Swift-style WebSocket Library (RFC 6455) for Swift-compatible Platforms. Tests Installation Requirements Usage Tests Conf

Gleb Radchenko 36 Jan 29, 2022
RSNetworking is a networking library written entirly for the Swift programming language.

RSNetworking is a networking library written entirly for the Swift programming language.

null 18 Feb 25, 2018
An awesome Swift HTML DSL library using result builders.

SwiftHtml An awesome Swift HTML DSL library using result builders. let doc = Document(.html5) { Html { Head { Meta()

Binary Birds 204 Dec 25, 2022
Plugin and runtime library for using protobuf with Swift

Swift Protobuf Welcome to Swift Protobuf! Apple's Swift programming language is a perfect complement to Google's Protocol Buffer ("protobuf") serializ

Apple 4.1k Jan 6, 2023
Swift library for working with LSP

LanguageServerProtocol This is a Swift library for interacting with Language Server Protocol. It contains type definitions and utilities useful for bo

Chime 35 Dec 30, 2022
ServiceData is an HTTP networking library written in Swift which can download different types of data.

ServiceData Package Description : ServiceData is an HTTP networking library written in Swift which can download different types of data. Features List

Mubarak Alseif 0 Nov 11, 2021