• Stars
    star
    576
  • Rank 74,540 (Top 2 %)
  • Language
    Swift
  • License
    Apache License 2.0
  • Created almost 8 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

NTP library for Swift and Objective-C. Get the true time impervious to device clock changes.

TrueTime for Swift Carthage compatible Travis CI

TrueTime

Make sure to check out our counterpart too: TrueTime, an NTP library for Android.

NTP client for Swift. Calculate the time "now" impervious to manual changes to device clock time.

In certain applications it becomes important to get the real or "true" date and time. On most devices, if the clock has been changed manually, then an NSDate() instance gives you a time impacted by local settings.

Users may do this for a variety of reasons, like being in different timezones, trying to be punctual and setting their clocks 5 – 10 minutes early, etc. Your application or service may want a date that is unaffected by these changes and reliable as a source of truth. TrueTime gives you that.

How is TrueTime calculated?

It's pretty simple actually. We make a request to an NTP server that gives us the actual time. We then establish the delta between device uptime and uptime at the time of the network response. Each time now() is requested subsequently, we account for that offset and return a corrected NSDate value.

Usage

Swift

import TrueTime

// At an opportune time (e.g. app start):
let client = TrueTimeClient.sharedInstance
client.start()

// You can now use this instead of NSDate():
let now = client.referenceTime?.now()

// To block waiting for fetch, use the following:
client.fetchIfNeeded { result in
    switch result {
        case let .success(referenceTime):
            let now = referenceTime.now()
        case let .failure(error):
            print("Error! \(error)")
    }
}

Objective-C

@import TrueTime;

// At an opportune time (e.g. app start):
TrueTimeClient *client = [TrueTimeClient sharedInstance];
[client startWithPool:@[@"time.apple.com"] port:123];

// You can now use this instead of [NSDate date]:
NSDate *now = [[client referenceTime] now];

// To block waiting for fetch, use the following:
[client fetchIfNeededWithSuccess:^(NTPReferenceTime *referenceTime) {
    NSLog(@"True time: %@", [referenceTime now]);
} failure:^(NSError *error) {
    NSLog(@"Error! %@", error);
}];

Notifications

You can also listen to the TrueTimeUpdated notification to detect when a reference time has been fetched:

let client = TrueTimeClient.sharedInstance
let _ = NSNotificationCenter.default.addObserver(forName: .TrueTimeUpdated, object: client) { _ in
    // Now guaranteed to be non-nil.
    print("Got time: \(client.referenceTime?.now()")
}

Installation Options

TrueTime is currently compatible with iOS 8 and up, macOS 10.10 and tvOS 9.

Carthage (recommended)

Add this to your Cartfile:

github "instacart/TrueTime.swift"

Then run:

$ carthage update

CocoaPods

Add this to your Podfile:

pod 'TrueTime'

Then run:

$ pod install

Manually

  • Run git submodule update --init.
  • Run carthage bootstrap.
  • Run brew install swiftlint if not already installed.
  • Open TrueTime.xcodeproj, choose TrueTimeExample and hit run. This will build everything and run the sample app.

Manually using git submodules

  • Add TrueTime as a submodule:
$ git submodule add https://github.com/instacart/TrueTime.swift.git
  • Follow the above instructions for bootstrapping manually.
  • Drag TrueTime.xcodeproj into the Project Navigator.
  • Go to Project > Targets > Build Phases > Link Binary With Libraries, click + and select the TrueTime target.

Notes / Tips

  • Since NSDates are just Unix timestamps, it's safe to hold onto values returned by ReferenceTime.now() or persist them to disk without having to adjust them later.
  • Reachability events are automatically accounted for to pause/start requests.
  • UDP requests are executed in parallel, with a default limit of 5 parallel calls. If one fails, we'll retry up to 3 times by default.
  • TrueTime is also available for Android.

Contributing

This project adheres to the Contributor Covenant code of conduct. By participating (including but not limited to; reporting issues, commenting on issues and contributing code) you are expected to uphold this code. Please report unacceptable behavior to [email protected].

Setup

Development depends on some Carthage dependencies and a xcconfig git submodule.

Clone the repo and setup dependencies with:

git submodule update --init --recursive
carthage bootstrap

License

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Learn more

NTP

More Repositories

1

lore

Lore makes machine learning approachable for Software Engineers and maintainable for Machine Learning Researchers
Python
1,549
star
2

truetime-android

Android NTP time library. Get the true current time impervious to device clock time changes
Kotlin
1,385
star
3

Nantes

Swift TTTAttributedLabel replacement
Swift
1,104
star
4

makara

A Read-Write Proxy for Connections; Also provides an ActiveRecord adapter.
Ruby
902
star
5

wilson_score

Simple, dependency-free Wilson score
Ruby
154
star
6

formula

A functional reactive framework for managing state and side effects based on RxJava.
Kotlin
147
star
7

ohmycron

Run cron jobs in a standardized environment with logs and locking
Shell
138
star
8

ahab

Docker event handling with Python
Python
137
star
9

amountable

An easy and transparent way to attach, manage and sum Money fields to your ActiveRecord models.
Ruby
122
star
10

jardin-archived

A pandas.DataFrame-based ORM.
Python
85
star
11

Snacks

The Instacart Component Library
JavaScript
79
star
12

redux-rails

Redux and your server talking without fuss.
JavaScript
56
star
13

arn

A Python library for parsing AWS ARNs.
Python
44
star
14

ahoy-android

Android attribution library build on top of Ahoy for Ruby on Rails.
Java
19
star
15

cwam

CloudWatch Alarms Manager. Easy way to create default CloudWatch Alarms for AWS resources.
Python
19
star
16

instacart-android-pp-sandbox

Android challenge sandbox
Kotlin
9
star
17

aws-scripts-mon

[TO BE DELETED] Clone of AWS Cloudwatch Monitor Scripts + report inodes
Perl
4
star
18

redux-rails-resource

Simple interface of redux-rails resources for react components
JavaScript
3
star
19

OmniAX

UIAccessibility wrapper
Swift
2
star
20

instacart-ios-pp-starter

Starter app to give candidates starting on pair programming exercise
Swift
2
star
21

ExploreRxSwift

Swift
2
star
22

cloudflare-rails

Ruby
2
star
23

SocketLogger.swift

Lightweight, flexible logging utility compatible with any socket-based syslog service.
Swift
2
star
24

optplayground

A playground for optimization!
Python
1
star
25

instacart-android-pp-starter

Starter app to give candidates starting on pair programming exercise
Java
1
star
26

activerecord-import_with_callbacks

A library for bulk importing data using ActiveRecord
Ruby
1
star