Created
February 22, 2016 14:01
-
-
Save kenechiokolo/804dfe3611eb8ddcd9c1 to your computer and use it in GitHub Desktop.
Code for NSTimer Tutorial
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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