Git Product home page Git Product logo

truetime.swift's Introduction

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.retrieveReferenceTime { 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 startWithHostURLs:@[[NSURL URLWithString:@"time.apple.com"]]];

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

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

Installation Options

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

Add this to your Cartfile:

github "instacart/TrueTime.swift"

Then run:

$ carthage update

Manually

  • Run git submodule update --init.
  • Run carthage bootstrap.
  • Open TrueTime.xcodeproj, choose TrueTimeExample and hit run. This will build everything and run the sample app.

Manually using submodules

(works alongside Cocoapods)

  • Add TrueTime as a submodule:
$ git submodule add https://github.com/instacart/TrueTime.swift.git
  • Navigate to the TrueTime directory and add its dependencies
$ carthage bootstrap
  • Install Swift Lint if missing
$ brew install swiftlint
  • 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.

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.

truetime.swift's People

Contributors

msanders avatar warpling avatar

Watchers

 avatar James Cloos avatar  avatar

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.