Skip to content

Instantly share code, notes, and snippets.

@kenechiokolo
Created February 22, 2016 14:01
Show Gist options
  • Save kenechiokolo/804dfe3611eb8ddcd9c1 to your computer and use it in GitHub Desktop.
Save kenechiokolo/804dfe3611eb8ddcd9c1 to your computer and use it in GitHub Desktop.
Code for NSTimer Tutorial
//
// ViewController.swift
// NSTimerTutorial
//
// Created by Kc on 22/02/2016.
// Copyright © 2016 Kenechi Okolo. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var timer: NSTimer?
var finishedWithTimer = false
var timerStartedAt: NSDate?
// MARK: Actions & Outlets
@IBOutlet weak var timeElapsed: UILabel!
@IBAction func startTimer(sender: UIButton) {
timerStartedAt = NSDate()
finishedWithTimer = false
timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "fire", userInfo: nil, repeats: false)
}
@IBAction func stopTimer(sender: UIButton) {
finishedWithTimer = true
}
func fire() {
timeElapsed.text = "Time since function last called: \(Int(NSDate().timeIntervalSinceDate(timerStartedAt!)))"
timerStartedAt = NSDate()
let number = randomNumberInRange(1, upper: 10)
timer = NSTimer.scheduledTimerWithTimeInterval(Double(number), target: self, selector: "fire", userInfo: nil, repeats: false)
timer?.tolerance = Double(number) / 10
if finishedWithTimer {
timer?.invalidate()
}
}
func randomNumberInRange(lower: Int, upper: Int) -> Int {
return lower + Int(arc4random_uniform(UInt32(upper - lower + 1)))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment