Swifty API for NSTimer

Overview

SwiftyTimer

Platforms CI Status CocoaPods Carthage compatible Swift version

Modern Swifty API for NSTimer

SwiftyTimer allows you to instantly schedule delays and repeating timers using convenient closure syntax. It's time to get rid of Objective-C cruft.

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

Usage

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

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

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

You can specify time intervals with these intuitive helpers:

100.ms
1.second
2.5.seconds
5.seconds
10.minutes
1.hour
2.days

You can pass method references instead of closures:

Timer.every(30.seconds, align)

Manual scheduling

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

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

(This should be defined as an initializer, but a bug in Foundation 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: .defaultRunLoopMode, .eventTrackingRunLoopMode)

Invalidation

If you want to invalidate a repeating timer on some condition, you can take a Timer argument in the closure you pass in:

Timer.every(5.seconds) { (timer: Timer) in
    // do something
    
    if finished {
        timer.invalidate()
    }
}

Installation

Note: If you're running Swift 2, use SwiftyTimer v1.4.1

CocoaPods

If you're using CocoaPods, just add this line to your Podfile:

pod 'SwiftyTimer'

Install by running this command in your terminal:

pod install

Then import the library in all files where you use it:

import SwiftyTimer

Carthage

Just add to your Cartfile:

github "radex/SwiftyTimer"

Manually

Simply copy Sources/SwiftyTimer.swift to your Xcode project.

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.

Comments
  • Include NSTimer in block?

    Include NSTimer in block?

    What are your thoughts about including the timer object in the block?

    public class func every(interval: NSTimeInterval, _ block: NSTimer -> Void) -> NSTimer {}
    

    Otherwise I need to declare the variable separately like this:

    var timer: NSTimer?
    timer = NSTimer.every(5.seconds) {
        timer?.invalidate()
    }
    
    opened by efremidze 7
  • Usage issue

    Usage issue

    I was wondering if you can clarify what the difference is between

    NSTimer.every(0.7.seconds) {
        println(self.status)
    }
    

    and

    let timer = NSTimer.new(every: 1.second) {
        println(self.status)
    }
    
    opened by pjebs 3
  • is it supposed to work on a background queue?

    is it supposed to work on a background queue?

    Thanks for sharing your work. Trying to do something apparently simple but I see nothing on the console and breakpoints don't stop there. What am I getting wrong?

    let backgroundQueue = DispatchQueue(label: "1sec",
        qos: .background,
        target: nil)
    
    backgroundQueue.async {
        Timer.every(1.seconds) {
            self.log.debug("Timer tick at \(Date())")
        }
    }
    

    Cheers

    opened by jaimeagudo 2
  • Support lower deployment targets than 10.11

    Support lower deployment targets than 10.11

    I haven't perused the source fully, but I would imagine there is no reason that 10.11 is the deployment target for this. I'm wanting to use it in a project that needs to support mavericks. My guess is it was an oversight, as it was in my project file.

    opened by jhoughjr 2
  • Use default arguments naming

    Use default arguments naming

    When I call a NSTimer.after and pass a function, it doesn't have a argument name for second argument. This feels not natural for me regarding that all other functions usually used default or external names.

      NSTimer.after(1.second, close)
    

    Using default names don't change the nice trailing closure syntax

    public class func after(interval: NSTimeInterval, block: () -> Void) -> NSTimer 
    ...
    NSTimer.after(1.second) {
      print("done")
    }
    

    If you agree I can make a PR :)

    opened by kostiakoval 2
  • Convert code base to swift 3.0 (Xcode 8.0 beta 2)

    Convert code base to swift 3.0 (Xcode 8.0 beta 2)

    @radex

    Fixes https://github.com/radex/SwiftyTimer/issues/27

    Most of the migration was done using Xcode's migration tool. It is mostly about renaming NSTimer to Timer.

    Minor thing to note: Swift 3 will now produce a warning of the result of Timer.<method> is unused.

    Let me know if you have any question.

    opened by ldiqual 1
  • Support for Swift Package Manager

    Support for Swift Package Manager

    Swift Package Manager

    • iOS: Open Xcode, File->Swift Packages, search input https://github.com/radex/SwiftyTimer.git, and then select Version Up to Next Major 2.1.1 < .
    • Or add dependencies in your Package.swift:
    .package(url: "https://github.com/radex/SwiftyTimer.git", .upToNextMajor(from: "2.1.1")),
    

    Please git a new tag to support it.

    opened by janlionly 0
  • Add the ability to specify RunLoop and RunLoopMode in `after` and `every` methods

    Add the ability to specify RunLoop and RunLoopMode in `after` and `every` methods

    This was required in my project to be able to use after and every methods for timers that need to update the UI. The timer needs to run in .commonModes to be able to update the UI while scrolling.

    It keep the same behaviour as previously and the signature is backward compatible. I added a new start function because the splat operator is not available in Swift, hence the need to create a new one that takes an array as parameters.

    Feedbacks are welcome, I will adjust the PR accordingly.

    opened by madeinqc 0
  • Can't figure out how to stop timer

    Can't figure out how to stop timer

    Hello!

    I want to make a function that starts the timer unless there is a bool true in params (e.g. animateStatusIcon(stop: true)) - in that case I want to stop the timer. Does anyone have an idea what's going on here?

    The timer starts but no matter what I do it wont stop.

    func animateStatusIcon(stop: Bool? = nil){
            
            let icon = NSImage(named: "statusIcon")
            let iconActive = NSImage(named: "statusIconActive")
            
            let timer = Timer.every(0.4.seconds) {
                self.statusItem.image = icon
                Timer.after(0.2.seconds) {
                    self.statusItem.image = iconActive
                }
            }
                
            if(stop == true){
                print(stop!)
                print("should stop now")
                timer.invalidate()
            } else  {
                print(stop)
                print("start")
                timer.start()
            }
            
        }
    
    opened by benjam1n 0
  • Crash when calling fire() after creating timer

    Crash when calling fire() after creating timer

    The following code worked with 1.3.0 but crashes with 1.4.0:

    let timer = NSTimer.every(1) { 
                print("do something!")
            }
    timer.fire()
    

    The internal refactoring of not using NSTimer initializers might be the problem.

    opened by BenchR267 10
Releases(2.1.0)
Owner
Radek Pietruszewski
Face shield manufacturer. Software writer. Proud generalist. Poking the box since 1995. Do you even Swift? 🚀â™ģī¸
Radek Pietruszewski
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
Schedule timing task in Swift using a fluent API. (A friendly alternative to Timer)

Schedule(įŽ€äŊ“中文) Schedule is a timing tasks scheduler written in Swift. It allows you run timing tasks with elegant and intuitive syntax. Features Elega

Luo Xiu 1.8k Dec 21, 2022
Typical master detail SAMPLE application written in Swift to test NY Times Most Popular API

NYTimes-Demo: Typical master detail SAMPLE application written in Swift to test NY Times Most Popular API. This SAMPLE application is written in Swift

Atif Naveed 0 Nov 3, 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
A swift wrapper for NSTimer

Every.Swift - A Convenient NSTimer Wrapper Usage Provided that your class implement TimerManageable protocol you just do: self.every(3.seconds) {

Samhan Salahuddin 271 Apr 14, 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
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
A Swifty API for attributed strings

SwiftyAttributes A Swifty API for attributed strings. With SwiftyAttributes, you can create attributed strings like so: let fancyString = "Hello World

Eddie Kaiger 1.5k Jan 5, 2023
Github API V3 Swifty Wrapper

GithubPilot - Github API V3 Swifty Wrapper This is a Swift Github API Wrapper, it could make your life a little easier if you want to make an App with

Yansong Li 53 Feb 2, 2022
A Swifty API for global macOS hotkeys.

A Swifty API for global macOS hotkeys. Install Add the following dependency to your Package.swift file: .package(url: "https://github.com/jordanbaird/

Jordan Baird 9 Dec 28, 2022
Swifty and modern UserDefaults

Defaults Swifty and modern UserDefaults Store key-value pairs persistently across launches of your app. It uses NSUserDefaults underneath but exposes

Sindre Sorhus 1.3k Jan 6, 2023
The most swifty way to deal with XML data in swift 5.

SwiftyXML SwiftyXML use most swifty way to deal with XML data. Features Infinity subscript dynamicMemberLookup Support (use $ started string to subscr

Kevin 99 Sep 6, 2022
A sweet and swifty YAML parser built on LibYAML.

Yams A sweet and swifty YAML parser built on LibYAML. Installation Building Yams requires Xcode 11.x or a Swift 5.1+ toolchain with the Swift Package

JP Simard 930 Jan 4, 2023
Fashion is your helper to share and reuse UI styles in a Swifty way.

Fashion is your helper to share and reuse UI styles in a Swifty way. The main goal is not to style your native apps in CSS, but use a set

Vadym Markov 124 Nov 20, 2022
Swifty, modern UIAlertController wrapper.

Alertift Alertift.alert(title: "Alertift", message: "Alertift is swifty, modern, and awesome UIAlertController wrapper.") .action(.default("❤ī¸"))

Suguru Kishimoto 287 Jan 7, 2023
🍞 Loaf is a Swifty Framework for Easy iOS Toasts

Loaf ?? Inspired by Android's Toast, Loaf is a Swifty Framework for Easy iOS Toasts Usage From any view controller, a Loaf can be presented by calling

Mat Schmid 995 Dec 28, 2022
Swifty closures for UIKit and Foundation

Closures is an iOS Framework that adds closure handlers to many of the popular UIKit and Foundation classes. Although this framework is a substitute f

Vinnie Hesener 1.7k Dec 21, 2022
A swifty iOS framework that allows developers to create beautiful onboarding experiences.

SwiftyOnboard is being sponsored by the following tool; please help to support us by taking a look and signing up to a free trial SwiftyOnboard A simp

Juan Pablo Fernandez 1.2k Jan 2, 2023
Swifty regular expressions

Regex Swifty regular expressions This is a wrapper for NSRegularExpression that makes it more convenient and type-safe to use regular expressions in S

Sindre Sorhus 311 Nov 22, 2022
Swifty TVML template manager with or without client-server

TVMLKitchen ?? ?? TVMLKitchen helps to manage your TVML with or without additional client-server. Requirements Swift3.0 tvOS 9.0+ Use 0.9.6 for Swift2

Toshihiro Suzuki 81 Nov 14, 2022