/SwiftyTimer

Swifty API for NSTimer

Primary LanguageSwiftMIT LicenseMIT

SwiftyTimer

SwiftyTimer is a set of extensions to make the NSTimer API cleaner, nicer to use, and at home with Swift's syntax.

Read Swifty APIs: NSTimer for more information about this project.

Usage

You can easily schedule repeating and non-repeating timers (repeats and delays) using NSTimer.every and NSTimer.after:

NSTimer.every(0.7.seconds) {
    statusItem.blink()
}

NSTimer.after(1.minute) {
    println("Are you still here?")
}

SwiftyTimer uses closures instead of target/selector/userInfo.

You can specify time intervals with intuitive Ruby on Rails-like helpers:

1.second
2.5.seconds
5.seconds
10.minutes
1.hour

You can pass method references instead of closures:

NSTimer.every(30.seconds, align)

If you want to make a timer object without scheduling, use new(after:) and new(every:):

let timer = NSTimer.new(every: 1.second) {
    println(self.status)
}

(This should be defined as an initializer, but a bug in Swift prevents this)

Call start() to schedule timers created using new. You can optionally pass the run loop and run loop modes:

timer.start()
timer.start(modes: NSDefaultRunLoopMode, NSEventTrackingRunLoopMode)

Installation

The simplest way to install this library is to copy Src/SwiftyTimer.swift to your project. There's no step two!

CocoaPods

You can also install this library using CocoaPods. Just add this line to your Podfile:

pod 'SwiftyTimer'

Then import library module like so:

import SwiftyTimer

Note that this requires CocoaPods 0.36+, as well as iOS 8 or OS X 10.9+

More like this

If you like SwiftyTimer, check out SwiftyUserDefaults, which applies the same swifty approach to NSUserDefaults.

You might also be interested in my blog posts which explain the design process behind those libraries:

Contributing

If you have comments, complaints or ideas for improvements, feel free to open an issue or a pull request.

Author and license

Radek Pietruszewski

SwiftyTimer is available under the MIT license. See the LICENSE file for more info.