Elegant ⏱ interface for Swift apps
Each is a NSTimer bridge library written in Swift.
- Completely configurable timers
- Support for time intervals in ms, seconds, minutes and hours
- Fully extendable
- More readable and simple to use in comparison with NSTimer object
- iOS 8.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+
- Xcode 8.0+
- Swift 3.0+
CocoaPods is a dependency manager for Cocoa projects. You can install it with the following command:
$ gem install cocoapods
CocoaPods 1.1.0+ is required to build Each 1.0.0+.
To integrate Each into your Xcode project using CocoaPods, specify it in your Podfile
:
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '10.0'
use_frameworks!
target '<Your Target Name>' do
pod 'Each', '~> 1.1'
end
Then, run the following command:
$ pod install
let timer = Each(1).seconds // Can be .milliseconds, .seconds, .minute, .hours
timer.perform {
// Do your operations
// This closure has to return a Boolean value
// Return .continue if you want to leave the timer active, otherwise
// return .stop to invalidate it
}
timer.stop() // This stops immediately the timer
You can restart the timer only after you stopped it. This method restarts the timer with the same perform closure.
timer.restart()
Unfortunately the interface doesn't help you with handling the memory leaks the timer could create. In case of them, two workarounds are provided
In case you don't want to declare a property that holds the Each
reference, create a normal Each
timer in your method scope and return .stop/true
whenever the owner
instance is nil
Each(1).seconds.perform { [weak self] in
guard let _ = self else { return .stop }
print("timer called")
return .continue
}
90% of closures will call self
somehow, so this isn't so bad
In case the first workaround wasn't enough, you can declare a property that holds the Each
reference and call the stop()
function whenever the owner
is deallocated
final class ViewController: UIViewController {
private let _timer = Each(1).seconds
deinit {
_timer.stop()
}
override func viewDidLoad() {
super.viewDidLoad()
_timer.perform {
// do something and return. you can check here if the `self` instance is nil as for workaround #1
}
}
}
Each is released under the MIT license. See LICENSE for details.