Elegant NTP date library in Swift

Related tags

Date & Time 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
A "time ago", "time since", "relative date", or "fuzzy date" category for NSDate and iOS, Objective-C, Cocoa Touch, iPhone, iPad

Migration 2014.04.12 NSDate+TimeAgo has merged with DateTools. DateTools is the parent project and Matthew York is the project head. This project is n

Kevin Lawler 1.8k Dec 2, 2022
Date Formatter Pool - is a small utility that creates and stores your Date Formatter for simpler reuse

Date Formatter Pool Date Formatter Pool - is a small utility that creates and stores your Date Formatter for simpler reuse Installation is available i

Aleksei Artemev 13 Sep 6, 2022
Building a better date/time library for Swift

Time Time is a Swift package that makes dealing with calendar values a natural and straight-forward process. Working with calendars can be extremely c

Dave DeLong 2k Dec 31, 2022
DateHelper - A high performant Swift Date Extension for creating, converting, comparing, or modifying dates.

DateHelper A high performant Swift Date Extension for creating, converting, comparing, or modifying dates. Capabilities Creating a Date from a String

Melvin Rivera 1.4k Jan 2, 2023
📆 Breeze through Date, DateComponents, and TimeInterval with Swift!

Datez ?? Breeze through Date, DateComponents, and TimeInterval Highlights Two Custom Structs Only (value types FTW!): DateView: An Date associated wit

Kitz 263 Dec 7, 2022
Intuitive date handling in Swift

Timepiece Intuitive date handling in Swift Features ?? Intuitive: Timepiece provides a set of helpers to make date handling easier. ?? Correct: Using

Naoto Kaneko 2.6k Dec 22, 2022
Swift Date Formatter

Swift Date Formatter Date Formatter - Sample code on how to use Date Formatter in swift language Author: Denow Cleetus For OSSE Assignment 4 Group 24

Denow Cleetus 0 Nov 7, 2021
NasaApod - iOS, Swift, MVVM, Consuming NASA Astronomy Picture of the Day API for any selected date

NasaApod iOS, Swift, MVVM, Unit Tests Consuming NASA Astronomy Picture of the Da

Vishal Singh 1 Jan 10, 2022
🎗 Super lightweight ISO8601 Date Formatter in Swift

ISO8601 ❤️ Support my apps ❤️ Push Hero - pure Swift native macOS application to test push notifications PastePal - Pasteboard, note and shortcut mana

Khoa 19 May 12, 2020
Date and time manager for iOS/OSX written in Swift

Tempo was designed to work both in OSX and in iOS (7.0+). Work with the time or dates can be cumbersome, iOS development. Tempo allows you to deal easly with date and time. Basics manipulations are already implemented in Tempo.

Remi ROBERT 153 Jun 3, 2021
Swifty Date & Time API inspired from Java 8 DateTime API.

AnyDate Swifty Date & Time API inspired from Java 8 DateTime API. Background I think that date & time API should be easy and accurate. Previous dates,

Jungwon An 182 Dec 1, 2022
Datify 🕛 Easypeasy date functions.

Datify ?? Easypeasy date functions.

Hemang 44 Dec 6, 2022
NVDate is an extension of NSDate class (Swift4), created to make date and time manipulation easier.

NVDate is an extension of NSDate class (Swift4), created to make date and time manipulation easier. NVDate is testable and robust, we wrote intensive test to make sure everything is safe.

Noval Agung Prayogo 177 Oct 5, 2022
A customizable date picker for watchOS and SwiftUI.

Watch Date Picker A customizable date picker for watchOS and SwiftUI. Installation .package(url: "https://github.com/freyaariel/watch-date-picker.git"

Freya Ariel 30 Dec 4, 2022
A basic countdown app that allows the user to create, edit, and delete events. Each event contains a live countdown timer to a specified date and time.

Event Countdown App (iOS) Created by Lucas Ausberger About This Project Created: January 4, 2021 Last Updated: January 8, 2021 Current Verison: 1.1.1

Lucas Ausberger 1 Jan 8, 2022
Swifty Date & Time API inspired from Java 8 DateTime API.

AnyDate Swifty Date & Time API inspired from Java 8 DateTime API. Background I think that date & time API should be easy and accurate. Previous dates,

Jungwon An 182 Dec 1, 2022
SwiftMoment - A time and calendar manipulation library for iOS 9+, macOS 10.11+, tvOS 9+, watchOS 2+ written in Swift 4.

SwiftMoment This framework is inspired by Moment.js. Its objectives are the following: Simplify the manipulation and readability of date and interval

Adrian Kosmaczewski 1.6k Dec 31, 2022
A Swift micro library for generating Sunrise and Sunset times.

Solar A Swift helper for generating Sunrise and Sunset times. Solar performs its calculations locally using an algorithm from the United States Naval

Chris Howell 493 Dec 25, 2022
Timekeeper is an easy-to-use time measurement library written in Swift, with support for iOS, tvOS, watchOS and macOS.

Timekeeper is an easy-to-use time measurement library written in Swift, with support for iOS, tvOS, watchOS and macOS. Installation Timekee

Andreas Pfurtscheller 1 Oct 18, 2021