Create timer on a scroll view - ios

How would I go about creating a timer function on a scroll view.
I have implemented a timer function that works correctly however due to the nature of a scrollView the view controller loads everytime the page is swiped & the timer gets reset.
How would I store the value of the timer from each page of the scrollView, so that it doesn't reset?
Below are my timer functions:
override func viewDidAppear(animated: Bool) {
// Start Timer Variables
startGame()
timerButtonStart()
}
Timer Functions
// Mark : Timer Functions
func startGame() {
let aSelector : Selector = "updateTime"
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: aSelector, userInfo: nil, repeats: true)
startTime = NSDate.timeIntervalSinceReferenceDate()
}
#IBAction func pauseTimer(sender: AnyObject) {
if timerPaused == false {
elapsedTime += startTimeDate.timeIntervalSinceNow
timer.invalidate()
timerPaused = true
} else {
let aSelector : Selector = "updateTime"
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)
startTimeDate = NSDate()
startTime = NSDate.timeIntervalSinceReferenceDate() + elapsedTime
timerPaused = false
}
}
func updateTime() {
var currentTime = NSDate.timeIntervalSinceReferenceDate()
//Find the difference between current time and start time.
var elapsedTime: NSTimeInterval = currentTime - startTime
//calculate the minutes in elapsed time.
let minutes = UInt8(elapsedTime / 60.0)
elapsedTime -= (NSTimeInterval(minutes) * 60)
//calculate the seconds in elapsed time.
let seconds = UInt8(elapsedTime)
elapsedTime -= NSTimeInterval(seconds)
//find out the fraction of milliseconds to be displayed.
let fraction = UInt8(elapsedTime * 100)
//add the leading zero for minutes, seconds and millseconds and store them as string constants
let strMinutes = minutes > 9 ? String(minutes):"0" + String(minutes)
let strSeconds = seconds > 9 ? String(seconds):"0" + String(seconds)
strMinutesGlobal = strMinutes
strSecondsGlobal = strSeconds
//concatenate minuets, seconds and milliseconds as assign it to the UILabel
timerLabel.text = "\(strMinutesGlobal!):\(strSecondsGlobal!)"
}
func timerButtonStart() {
var refreshButton = UIBarButtonItem(barButtonSystemItem: .Refresh, target: self, action: "timer") //Use a selector
navigationItem.leftBarButtonItem = refreshButton
navigationController!.navigationBar.barTintColor = UIColor.greenColor()
title = "Search result"
}

If you want to prevent that your NSTimer gets deallocated when switching view controllers, you could store the NSTimer instance in a separate singleton class instead of the view controller.
class MyTimer {
var sharedInstance = MyTimer()
var timer: NSTimer?
}
With this, you can access the NSTimer instance like this:
MyTimer.sharedInstance.timer

You can change your timer creation code to
if (timer == nil) {
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: aSelector, userInfo: nil, repeats: true)
}
and also when you invalidate your timer you will need to set it to nil. This will only recreate the timer if it doesn't already exist.

Related

How can I prevent the stopwatch from resetting after pause

When I hit Pause it pauses the timer. but then when I hit start, it resets to 0 instead of continue where it left off. How can I fix this?
I've tried adding a new button for reset. that works, but now I can't get the start button to keep counting after a pause. I've been struggling with getting the resume to work.
import UIKit
class TimerViewController: UIViewController {
#IBOutlet weak var lable: UILabel!
#objc var startTime = TimeInterval()
var timer = Timer()
override func viewDidLoad(){
super.viewDidLoad()
}
// Start Button
#IBAction func start(_ sender: UIButton) {
if (!timer.isValid) {
let aSelector = #selector(updateTime)
timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)
startTime = NSDate.timeIntervalSinceReferenceDate
}
}
// Pause Button
#IBAction func pause(_ sender: UIButton)
{
timer.invalidate()
}
// Reset Button
#IBAction func reset(_ sender: UIButton)
{
timer.invalidate()
lable.text = "00:00:00"
}
#objc func updateTime() {
let currentTime = NSDate.timeIntervalSinceReferenceDate
//Find the difference between current time and start time.
var elapsedTime: TimeInterval = currentTime - startTime
//calculate the minutes in elapsed time.
let minutes = UInt8(elapsedTime / 60.0)
elapsedTime -= (TimeInterval(minutes) * 60)
//calculate the seconds in elapsed time.
let seconds = UInt8(elapsedTime)
elapsedTime -= TimeInterval(seconds)
//find out the fraction of milliseconds to be displayed.
let fraction = UInt8(elapsedTime * 100)
//add the leading zero for minutes, seconds and millseconds and store them as string constants
let strMinutes = String(format: "%02d", minutes)
let strSeconds = String(format: "%02d", seconds)
let strFraction = String(format: "%02d", fraction)
//concatenate minuets, seconds and milliseconds as assign it to the UILabel
lable.text = "\(strMinutes):\(strSeconds):\(strFraction)"
}
}
keep the startTime variable from being modified until it is reset. maybe for example like this
var isReset: Bool = true
#IBAction func start(_ sender: UIButton) {
if (!timer.isValid) {
let aSelector = #selector(updateTime)
timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)
if isReset {
startTime = NSDate.timeIntervalSinceReferenceDate
isReset = false
}
}
}
#IBAction func reset(_ sender: UIButton) {
timer.invalidate()
lable.text = "00:00:00"
isReset = true
}
Cheers...

How to add countdowntimer which will run in whole iOS application?

I need to add a global timer of 60 minutes in the application which will show in all ViewControllers.
But not able to implement this feature.
I have implemented timer in one ViewController till now.
Here is my code:
var timerCount = 3600
var timer = Timer()
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(update), userInfo: nil, repeats: true)
func update() {
if(timerCount > 0){
let minutes = String(timerCount / 60)
let seconds = String(timerCount % 60)
timeLbl.text = minutes + ":" + seconds
timerCount -= 1
}
else {
timer.invalidate()
let vc = storyboard?.instantiateViewController(withIdentifier: "NavigateViewController")
navigationController?.pushViewController(vc!, animated: true)
}
}
I need to show this timer value in every ViewController of the application.
// Create class TimerManager
class TimerManager {
var timerCount = 3600
static let sharedInstance = TimerManager()
var timer: Timer?
init() {
self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(update), userInfo: nil, repeats: true)
}
#objc func update() {
if(timerCount > 0){
let minutes = String(timerCount / 60)
let seconds = String(timerCount % 60)
timerCount -= 1
}
else {
self.timer?.invalidate()
}
}
}
// At view Controller you can access timerCount
print(TimerManager.sharedInstance.timerCount)
You should display it in a separate UIWindow instance. Put the label in a separate View Controller and refer to answer 42 from this post:
To create a new UIWindow over the main window
// Create class TimerManager
class TimerManager {
var timerCount = 3600
static let sharedInstance = TimerManager()
var timer: Timer!
init() {
self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(update), userInfo: nil, repeats: true)
}
#objc func update() {
if(timerCount > 0){
let minutes = String(timerCount / 60)
let seconds = String(timerCount % 60)
timerCount -= 1
}
else {
self.timer?.invalidate()
}
}
}
// At view Controller you can access timerCount
print(TimerManager.sharedInstance.timerCount)

Pausing and Resuming a Timer in iOS

This is a bit of a common question but most answers don't seem to work. I have a timer in my app that and I can start and re-start the timer easily. I am trying to pause and resume the timer but for now resuming only continues the timer from a timer that's greater than the one I resumed it at. Which probably means it continues counting in the background. This is my code :
//Timer Variables
var startTime = NSTimeInterval()
var timer = NSTimer()
var isTiming = Bool()
var isPaused = Bool()
func updatedTimer() {
let currentTime = NSDate.timeIntervalSinceReferenceDate()
var elapsedTime: NSTimeInterval = currentTime - startTime
let minutes = UInt8(elapsedTime / 60.0)
elapsedTime -= (NSTimeInterval(minutes) * 60)
let seconds = UInt8(elapsedTime)
elapsedTime -= NSTimeInterval(seconds)
let strMinutes = String(format: "%02d", minutes)
let strSeconds = String(format: "%02d", seconds)
workoutTime.text = "\(strMinutes) : \(strSeconds)"
}
#IBAction func startButtonTapped(sender: AnyObject) {
if !timer.valid {
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: #selector(TimedWorkoutViewController.updatedTimer), userInfo: nil, repeats: true)
startTime = NSDate.timeIntervalSinceReferenceDate()
}
isTiming = true
isPaused = false
}
#IBAction func pauseAndContinueButtonTapped(sender: AnyObject) {
if isTiming == true && isPaused == false {
timer.invalidate() //Stop the Timer
isPaused = true //isPaused
isTiming = false //Stopped Timing
pauseButton.setTitle("RESUME", forState: UIControlState.Normal) //Set Button to Continue state
print(startTime)
} else if isTiming == false && isPaused == true {
if !timer.valid {
timer.invalidate()
//timer = nil
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: #selector(TimedWorkoutViewController.updatedTimer), userInfo: nil, repeats: true)
}
isPaused = false
isTiming = true
pauseButton.setTitle("PAUSE", forState: UIControlState.Normal) //Set Button to Continue state
}
}
I have a custom timer application and dealt with the same issue. There are many ways to address this. You may want to track pausedTime like you do elapsedTime and subtract that from your other variables. This gives you some flexibility as well to show totalTime vs. elapsedTime, etc... My function is quite a bit different, so I retrofitted it to your setup.
Basically, pausing is different because you can pause/resume multiple times. So you need to track previous pauses, and current pause state and subtract from elapsed time (or total time, or whatever you want).
I tested this code and it worked. Give it a try and let me know:
import UIKit
class TimedWorkoutViewController: UIViewController {
#IBOutlet weak var pauseButton: UIButton!
#IBOutlet weak var startButton: UIButton!
var startTime = NSTimeInterval()
var timer = NSTimer()
var isTiming = Bool()
var isPaused = Bool()
var pausedTime: NSDate? //track the time current pause started
var pausedIntervals = [NSTimeInterval]() //track previous pauses
override func viewDidLoad() {
super.viewDidLoad()
}
func updatedTimer() {
let currentTime = NSDate.timeIntervalSinceReferenceDate()
var pausedSeconds = pausedIntervals.reduce(0) { $0 + $1 } //calculate total time timer was previously paused
if let pausedTime = pausedTime {
pausedSeconds += NSDate().timeIntervalSinceDate(pausedTime) //add current pause if paused
}
var elapsedTime: NSTimeInterval = currentTime - startTime - pausedSeconds //subtract time paused
let minutes = Int(elapsedTime / 60.0)
elapsedTime -= (NSTimeInterval(minutes) * 60)
let seconds = Int(elapsedTime)
elapsedTime -= NSTimeInterval(seconds)
let strMinutes = String(format: "%02d", minutes)
let strSeconds = String(format: "%02d", seconds)
workoutTime.text = "\(strMinutes) : \(strSeconds)"
}
#IBAction func startButtonTapped(sender: AnyObject) {
if !timer.valid {
timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: #selector(TimedWorkoutViewController.updatedTimer), userInfo: nil, repeats: true)
startTime = NSDate.timeIntervalSinceReferenceDate()
}
isTiming = true
isPaused = false
pausedIntervals = [] //reset the pausedTimeCollector on new workout
}
#IBAction func pauseAndContinueButtonTapped(sender: AnyObject) {
if isTiming == true && isPaused == false {
timer.invalidate() //Stop the Timer
isPaused = true //isPaused
isTiming = false //Stopped Timing
pausedTime = NSDate() //asuuming you are starting a brand new workout timer
pauseButton.setTitle("RESUME", forState: UIControlState.Normal) //Set Button to Continue state
} else if isTiming == false && isPaused == true {
let pausedSeconds = NSDate().timeIntervalSinceDate(pausedTime!) //get time paused
pausedIntervals.append(pausedSeconds) // add to paused time collector
pausedTime = nil //clear current paused state
if !timer.valid {
timer.invalidate()
//timer = nil
timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: #selector(TimedWorkoutViewController.updatedTimer), userInfo: nil, repeats: true)
}
isPaused = false
isTiming = true
pauseButton.setTitle("PAUSE", forState: UIControlState.Normal) //Set Button to Continue state
}
}
}
Here is some code I once used to track time
class TimeTracker : NSObject {
private var startTime:NSTimeInterval?
private var timer:NSTimer?
private var elapsedTime = 0.0
private var pausedTimeDifference = 0.0
private var timeUserPaused = 0.0
var delegate:TimeTrackerDelegate?
func setTimer(timer:NSTimer){
self.timer = timer
}
func isPaused() -> Bool {
return !timer!.valid
}
func start(){
if startTime == nil {
startTime = NSDate.timeIntervalSinceReferenceDate()
newTimer()
}
}
func pause(){
timer!.invalidate()
timeUserPaused = NSDate.timeIntervalSinceReferenceDate()
}
func resume(){
pausedTimeDifference += NSDate.timeIntervalSinceReferenceDate() - timeUserPaused;
newTimer()
}
func handleTimer(){
let currentTime = NSDate.timeIntervalSinceReferenceDate()
elapsedTime = currentTime - pausedTimeDifference - startTime!
delegate!.handleTime(elapsedTime)
}
func reset(){
pausedTimeDifference = 0.0
timeUserPaused = 0.0
startTime = NSDate.timeIntervalSinceReferenceDate()
newTimer()
}
private func newTimer(){
timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target:self , selector: "handleTimer", userInfo: nil, repeats: true)
}
}

How to change the NSTimeInterval of an NSTimer after X seconds?

I'm making an app in swift 2 where there is two timers. After 10 seconds I would like another timer to go faster. I have tried doing it like this but it didn't work (I'm trying to change the var time to 1):
#IBOutlet var displayTimeLabel: UILabel!
var startTimer = NSTimeInterval()
var timer = NSTimer()
var timer2:NSTimer = NSTimer()
var time = 2.0
#IBAction func Start(sender: UIButton) {
if !timer2.valid {
timer2 = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "updateTime", userInfo: nil, repeats: true)
startTimer = NSDate.timeIntervalSinceReferenceDate()
}
timer = NSTimer.scheduledTimerWithTimeInterval(time, target: self, selector: "timer:", userInfo: nil, repeats: true)
}
func timer(timer: NSTimer){
//code
}
func updateTime() {
if displayTimeLabel.text >= "00:10.00"{
print("00:10.00") //works
time = 1 // trying to execute code after 10 seconds(doesn't work)
}
let currentTime = NSDate.timeIntervalSinceReferenceDate()
var elapsedTime: NSTimeInterval = currentTime - startTimer
let minutes = UInt8(elapsedTime / 60.0)
elapsedTime -= (NSTimeInterval(minutes) * 60)
let seconds = UInt8(elapsedTime)
elapsedTime -= NSTimeInterval(seconds)
let fraction = UInt8(elapsedTime * 100)
let strMinutes = String(format: "%02d", minutes)
let strSeconds = String(format: "%02d", seconds)
let strFraction = String(format: "%02d", fraction)
displayTimeLabel.text = "\(strMinutes):\(strSeconds).\(strFraction)"
}
If I write print(time) in func timer, after ten seconds it will print 1 instead of 2 but it will still be repeating every two second. Please help. To be clear, I want to be able to change time to 1 instead of 2 after ten seconds. I also don't want to invalidate the timers. The timers are also on repeat = true. Thanks in advance... Anton
A few of things.
First, you can't change the time interval of a repeating NSTimer - you need to invalidate the first timer and schedule a new one for the new interval.
Second a >= comparison on a string won't work for what you are trying to achieve.
Finally, you have fallen into the same bad habit as many Swift programmers and initialised your timer variables needlessly only to subsequently throw those timers away. You should use either an optional or an implicitly unwrapped optional
#IBOutlet var displayTimeLabel: UILabel!
var startTime:NSDate?
var timer : NSTimer?
var timer2: NSTimer?
var time = 2.0
#IBAction func Start(sender: UIButton) {
if (self.timer2 == nil) {
self.time=2.0
self.timer2 = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "updateTime", userInfo: nil, repeats: true)
self.startTime = NSDate()
self.timer = NSTimer.scheduledTimerWithTimeInterval(time, target: self, selector: "timer:", userInfo: nil, repeats: true)
}
}
func timer(timer: NSTimer){
//code
}
func updateTime() {
let currentTime = NSDate.timeIntervalSinceNow()
var elapsedTime = -self.startTime!.timeIntervalSinceNow()
if (elapsedTime >10.0 && self.time==2.0) {
timer.invalidate()
self.time=1.0
self.timer = NSTimer.scheduledTimerWithTimeInterval(time, target: self, selector: "timer:", userInfo: nil, repeats: true)
}
let minutes = UInt8(elapsedTime / 60.0)
elapsedTime -= (NSTimeInterval(minutes) * 60)
let seconds = UInt8(elapsedTime)
elapsedTime -= NSTimeInterval(seconds)
let fraction = UInt8(elapsedTime * 100)
displayTimeLabel.text = String(format: "%02d:%02d.%02d", minutes,seconds,fraction)
}
Just setting time = 1 will not modify timer.
The timeInterval of a timer can not be changed. Your only options are to create a new timer or start it with a timeInterval of 1 and just do nothing every other time timer() is called until the 10 sec have passed.

Resuming an NSTimer in Swift

The other questions I've seen on this didn't help. I want to be able to start, pause, and then resume the NSTimer. I know how to start the NSTimer. I also know that you can't 'pause' the NSTimer but you can invalidate it. But what would I have to do if I wanted to resume it keeping the same time I had when I stopped the timer? Here's the code:
var startTimer = NSTimeInterval()
var timer = NSTimer()
#IBOutlet var displaylabel: UILabel!
#IBAction func start(sender: UIButton) {
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "updateTime", userInfo: nil, repeats: true)
startTimer = NSDate.timeIntervalSinceReferenceDate()
}
#IBAction func stop(sender: UIButton) {
timer.invalidate()
}
#IBAction func resume(sender: UIButton) {
// Code needed
}
func updateTime() {
let currentTime = NSDate.timeIntervalSinceReferenceDate()
var elapsedTime: NSTimeInterval = currentTime - startTimer
let minutes = UInt8(elapsedTime / 60.0)
elapsedTime -= (NSTimeInterval(minutes) * 60)
let seconds = UInt8(elapsedTime)
elapsedTime -= NSTimeInterval(seconds)
let fraction = UInt8(elapsedTime * 100)
let strMinutes = String(format: "%02d", minutes)
let strSeconds = String(format: "%02d", seconds)
let strFraction = String(format: "%02d", fraction)
displaylabel.text = "\(strMinutes):\(strSeconds).\(strFraction)"
}
Thanks in advance. Anton
You should use a CADisplayLink for two reasons:
You'll update the screen as often as possible and not waste extra battery life trying to update it more often than possible. All iOS devices (except the iPad Pro under rare circumstances) update the screen at most 60 times per second. Scheduling your timer for 0.01 seconds means you're trying to update the screen at least 40 times per second more often than necessary.
You can pause and resume a CADisplayLink.
Handling pause requires a little thought. What you want to do is record the time when you pause (separately from the start time), and then when you resume, increase the start time by the time elapsed since pausing.
class ViewController: UIViewController {
private var startTime = NSTimeInterval(0)
private var pauseTime = NSTimeInterval(0)
private var displayLink: CADisplayLink!
#IBOutlet var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
displayLink = CADisplayLink(target: self, selector: "displayLinkDidFire")
displayLink.paused = true
displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes)
}
#IBAction func startWasTapped(sender: AnyObject) {
startTime = NSDate.timeIntervalSinceReferenceDate()
displayLink.paused = false
}
#IBAction func resumeWasTapped(sender: AnyObject) {
startTime += NSDate.timeIntervalSinceReferenceDate() - pauseTime
displayLink.paused = false
}
#IBAction func stopWasTapped(sender: AnyObject) {
pauseTime = NSDate.timeIntervalSinceReferenceDate()
displayLink.paused = true
}
func displayLinkDidFire() {
let elapsedTime = NSDate.timeIntervalSinceReferenceDate() - startTime
label.text = String(format: "%02.0f:%05.2f", floor(elapsedTime / 60), elapsedTime)
}
}

Resources