Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to continue a function across ViewControllers using Swift?

I have a NSTimer() that starts upon a button click. If I want the timer to be displayed on a label, I can do that within the same view controller, but I would like the timer to continue and the values (1...2...3) to be displayed on the next view controller. I have a label that displays the time variable on the next view controller but it only displays the value of the time variable when the button is pressed and does not continue. The time variable is passed but the function that runs it is not. How can I go about doing that?

var timer = NSTimer()

var time = 0

inside viewDidLoad :

timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("timerFunc"), userInfo: nil, repeats: true)

    func timerFunc() {

        time++

//time label displays the time (1..2...3 etc)

        timeLabel.text = String(time)

    }

SecondSceneViewController has a time variable that is passed from this view controller:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
            var secondScene = segue.destinationViewController as!           
                              SecondViewController

            secondScene.time = time
    }

When I go to the secondViewController, the value inside the time variable is whatever the time variable was when the button was pressed and it does not continue running. How would I go about passing the timer to the next view controller to display the values?

like image 762
IvOS Avatar asked Feb 07 '23 14:02

IvOS


1 Answers

IMO you should extract the code for the timer into a Singleton and then access it from both ViewControllers

Here's a simple one to get you started:

class TimerManager {

var realSharedInstance: TimerManager?
var sharedInstance: TimerManager {
    get{
        if let realSharedInstance = realSharedInstance {
            return realSharedInstance
        }
        else{
            realSharedInstance = TimerManager()
            return realSharedInstance!
        }
    }
}

var timer: NSTimer

init() {
    timer = NSTimer()
}

func rest() {
    timer = NSTimer()
}

}

like image 102
GetSwifty Avatar answered Feb 13 '23 05:02

GetSwifty