Swift - Timer doesn't stop - ios

I have the following code:
class firstVC: UIViewController {
var timer : Timer?
func scheduledTimerWithTimeInterval(){
timer = Timer.scheduledTimer(timeInterval: 60, target: self,
selector: #selector(self.anotherFunc), userInfo: nil, repeats:
true)
}
override func viewDidAppear(_ animated: Bool) {
scheduledTimerWithTimeInterval()
}
}
I'm trying to stop the timer without success:
func stopTimer() {
if timer != nil {
timer?.invalidate()
timer = nil
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
stopTimer()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
stopTimer()
}
I even tried to put the stop function in applicationWillResignActive
And in applicationDidEnterBackground but it didn't stop:
firstVC().stopTimer()
Your help will be appreciated, thank you.

As others have said, you are creating multiple timers without killing the old one before starting a new one. You need to make sure you stop any current timer before starting a new one.
What I do is to make my timers weak. I then use the code `myTimer?.invalidate() before trying to create a new timer:
class firstVC: UIViewController {
weak var timer : Timer?
func scheduledTimerWithTimeInterval(){
timer?.invalidate()
timer = Timer.scheduledTimer(timeInterval: 60, target: self,
selector: #selector(self.anotherFunc), userInfo: nil, repeats:
true)
}
}
By making your timer weak, the only thing that keeps a strong reference to the timer is the run loop. Then, when you invalidate it, it immediately gets released and set to nil. By using optional chaining to call the invalidate method, it doesn't do anything if it's already nil, and stops it and causes it to go nil if it IS running.
Note that this approach only works if you create your timer in one shot using one of the scheduledTimer() factory methods. If you try to create a timer first and then add it to the run loop, you have to use a strong local variable to create it or it gets released as soon as you create it.

The problem is your timer gets instantiated more than once, so the original timer loses its reference.
Add a variable didStartTimer = false.
And then in viewDidAppear do a validation, and then call the timer func.
That should do it.
like this:
class firstVC: UIViewController {
var timer : Timer?
var didStartTimer = false
func scheduledTimerWithTimeInterval(){
timer = Timer.scheduledTimer(timeInterval: 60, target: self,
selector: #selector(self.anotherFunc), userInfo: nil, repeats:
true)
}
override func viewDidAppear(_ animated: Bool) {
if !didStartTimer {
scheduledTimerWithTimeInterval()
didStartTime = true
}
}

After research I found a solution,
The only thing that worked for me is to create functions in AppDelegate file and call them when needed,
Here is the code, the timerSwitch function:
func timerSwitch()
{
if (timerStatus) {
checkStateTimer = Timer.scheduledTimer(
timeInterval: 60,
target:self,
selector: #selector(self.yourFunction),
userInfo: nil, repeats: true)
} else {
checkStateTimer?.invalidate()
}
}
func stopTimer()
{
timerStatus = false
timerSwitch()
}
func startTimer()
{
timerStatus = true
timerSwitch()
}
While 'yourFunction' is what you want to execute when the timer starts,
In my case is sending heartbeat.
Then I called the timerSwitch is the following functions in AppDelegate:
func applicationWillResignActive(_ application: UIApplication) {
stopTimer()
}
func applicationDidEnterBackground(_ application: UIApplication) {
stopTimer()
}
func applicationDidBecomeActive(_ application: UIApplication) {
startTimer()
}

As a debugging step, try putting var timer = Timer() in the global space (e.g. at the top of the file below the import statements) to make sure there's only one Timer object being created and referred to. If you have the Timer declaration within a function, you'll make a new timer each time you call that function, which causes you to lose the reference to the old one, and ultimately not stop it.

Nothing works for me, at last using self did the trick!!!
self.atimer?.invalidate()
self.atimer = Timer()

Related

How to start timer with open ViewController?

I want to create a timer, which goes on while i switch to an another ViewController and come back later. My solution is this way:
I start the timer with an button
then i hand over the integer to the next ViewController
I start the timer with the new integer
So my problem results in step three: I want to start the timer in the function viewDidLoad(). But the timer doesn't starts in the next ViewController.
i hope anybody can help me. Tell me, if there is a better way to do the things i want.
Here is my Code:
var timer = Timer()
var eighthours: Int = 8
var activejob: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
identify_activejob()
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(Jobs.jobtime), userInfo: nil, repeats: true)
}
//functions
#objc func jobtime() {
eighthours -= 1
}
I can show you one way. But may as suggested, it has native design flaw and use it depends on the accuracy.
let timer = Timer.init(timeInterval: 1, repeats: true) { (timer) in
let string = ISO8601DateFormatter().string(from: Date())
print("running" + string)
}
}
class TimerViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
RunLoop.main.add(timer, forMode: RunLoop.Mode.default)
// Do any additional setup after loading the view.
}
}
It will keep running until invalidate.
A couple of thoughts:
The eighthours -= 1 in the timer handler is slightly problematic, because it’s presuming that the Timer will fire, without interruption, at the desired timeInterval. But you should accommodate for interruptions in the Timer (e.g. the UI is blocked momentarily for some reason, the user completely leaves the app and returns, etc.).
We often shift from “decrement some counter with every call of the timer handler” to “figure out at what time we want the timer to expire”. This decouples the “model” (the stop time) from the “view” (the frequency with which the UI is updated). By doing this, if you later decide to update your UI with greater frequency (e.g showing milliseconds rather than seconds, probably using CADisplayLink instead of Timer), it doesn’t change the model driving the app. And it makes your app invulnerable to momentary interruptions that might affect the timer.
If you adopt this pattern, then you can pass around this “stop time”, your model, from view controller to view controller, and each view controller can start and stop its own timer as required by the desired UX for that scene.
So, to start a timer that will stop in 8 seconds:
var stopTime: Date? // set this when you start the timer
func startTimer() {
stopTime = Date().addingTimeInterval(8)
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(jobtime(_:)), userInfo: nil, repeats: true)
}
And the timer handler can determine how much time is left with timeIntervalSince to calculate the floating point difference, in seconds, between two dates.
#objc func jobtime(_ timer: Timer) {
let now = Date()
guard let stopTime = stopTime, now < stopTime else {
timer.invalidate()
return
}
let timeRemaining = stopTime.timeIntervalSince(now)
...
}
I also updated jobtime with a timer parameter so that you can see at a glance that it’s a Timer handler.
FYI, your code introduces a strong reference to the view controller that will prevent it from ever being released. This selector-based Timer keeps a strong reference to its target and the run loop keeps a reference to the Timer, so your view controller won’t be released until you invalidate the Timer.
There are a couple of solutions to this:
Start and stop timers as views appear and disappear:
weak var timer: Timer?
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(jobtime(_:)), userInfo: nil, repeats: true)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
timer?.invalidate()
}
#objc func jobtime(_ timer: Timer) { ... }
Note, we’re doing this in viewDidAppear and viewDidDisappear (rather than viewDidLoad) to ensure that the starting and stopping of timers is always balanced.
The other pattern is to use block-based Timer, use [weak self] reference to avoid having timer keeping strong reference to the view controller, and then you can invalidate it in the deinit method:
weak var timer: Timer?
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] timer in
self?.jobtime(timer)
}
}
deinit {
timer?.invalidate()
}
Finally, if you want to update the UI with the greatest possible frequency (e.g. to show milliseconds), you’d probably use a CADisplayLink which is a special timer, perfectly timed for UI updates:
private weak var displayLink: CADisplayLink?
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let displayLink = CADisplayLink(target: self, selector: #selector(jobtime(_:)))
displayLink.add(to: .main, forMode: .common)
self.displayLink = displayLink
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
displayLink?.invalidate()
}
#objc func jobtime(_ displayLink: CADisplayLink) { ... }
But the common feature in all of these approaches is that (a) we eliminate strong references from persisting that will interfere with the view controller from getting deallocated when appropriate; and (b) we let every view controller update its UI with whatever frequency it wants.

swift3,my timer can't stop. why?

this is i seting a timer function, the code like this:
#IBAction func start(_ sender: UIButton) {
Timer.scheduledTimer(timeInterval: 1,
target: self,
selector:#selector(ViewController.action),
userInfo: nil,
repeats: true)
}
#objc func action() {
hoursMinutesSeconds()
if stop == true{
start = false
timer.invalidate()
timer.invalidate()
time = 0
}
}
#IBAction func stop(_ sender: UIButton){
start = false
timer.invalidate()
timer.invalidate()
time = 0
}
but, when i click the stop func, this function not work. mean is the timer not stop. timer stil working…… why? thank you for your time!!
I think you didn't set timer value
timer = Timer.scheduledTimer(timeInterval: 1,
target: self,
selector:#selector(ViewController.action),
userInfo: nil,
repeats: true)
First you have to declare it as fileprivate as below:
fileprivate var timer = Timer()
#IBAction func start(_ sender: UIButton) {
self.timer = Timer.scheduledTimer(timeInterval: 4,
target: self,
selector: #selector(self.updateTimerForLocation),
userInfo: nil,
repeats: true)
}
#IBAction func stop(_ sender: UIButton) {
timer.invalidate()
}
Ensure that you are invalidating correct instance of Timer.
Like in start function, you didn't assign timer instance to any object, but in stop function,you are using timer vaiable to stop that timer.
Which means you try to invalidate a variable, which never instantiated.
Still try below function to stop timer, after assigning timer variable.
#IBAction func stop(_ sender: UIButton) {
start = false
timer.invalidate()
timer = nil
time = 0
}
Hope this work
you are confusing between variable stop and func stop.
also you dont need 2 parameter to manage stop/start status
--
for your question,
you should retain the timer variable to able to use it in other func
declare a global timer
var timer: Timer!
then
timer = Timer.scheduledTimer(timeInterval: 1,
target: self,
selector:#selector(ViewController.action),
userInfo: nil,
repeats: true)
now you can invalidate it anywhere

How to access a variable from another function?

I want to access myTimer variable from startTimer() function inside my backBtnPressed() function. Basically i want to add this code myTimer.invalidate() inside my backBtnPressed() function. How can i achieve that?
func startTimer() {
var myTimer = Timer.scheduledTimer(timeInterval: 3.0,
target: self,
selector: #selector(scrollToNextCell),
userInfo: nil,
repeats: true)
}
#IBAction func backBtnPressed(_ sender: UIButton) {
audioPlayer.stop()
}
As it stands now, you cannot access myTimer variable outside startTimer(), because it is outside the scope. For that, you need to declare myTimer as a Class variable. Them, you need to initialize it, as you are doing, and them you can access whatever you want inside the Class. Also don't forget to call startTimer, or it will return nil.
It looks more or less like this:
class YourViewController: ViewController {
var myTimer: Timer?
//some of your functions here
//...
override func viewDidLoad() {
super.viewDidLoad()
//...
startTimer()
}
func startTimer() {
myTimer = Timer.scheduledTimer(timeInterval: 3.0,
target: self,
selector: #selector(yourFunction),
userInfo: nil,
repeats: true)
}
#IBAction func backBtnPressed(_ sender: UIButton) {
//do whatever you want
myTimer.invalidate()
}
}
Simple make your timer a property:
class MyClass {
var timer: Timer?
func startTimer() {
timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(scrollToNextCell), userInfo: nil, repeats: true)
}
#IBAction func backBtnPressed(_ sender: UIButton) {
audioPlayer.stop()
timer.//do something with timer
}
}

Check for any timers running in any ViewController

I create and start a self-repeating timer in one of my ViewControllers (let's call it VC1) to have some kind of slideshow of images. When transitioning to any other VC the timer of VC1 appears to keep running as its selector method prints stuff every two seconds. Since this interferes with the timer when returning to VC1 from any other VC I have to remove it at some point.
This is what happens in the console: (runImages() is the timer's selector, the number is the image that should be displayed, as you see its weird...)
I thought the timer would stop once I exit VC1 since I do not save it anywhere. Since this is not the case I thought I might remove the timer when leaving VC1. Is there a method that is being called when VC1 is about to be dismissed?
Another approach I had in mind was removing any timers at the beginning of source code of the other VCs. So, when I enter VC2 I want to check for any timers that are running in the project. Is there a way to do that without making the timer a global variable accessible to all VCs?
Code Reference
This is how I create the timer: (outside a method)
var timer: NSTimer!
Then, in a method I set it:
timer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "runImages:", userInfo: nil, repeats: true)
runImage() then increases i and calls changeImage() which transitions my imageView's image to the image named like i.
Thanks in advance :)
Update
I made the timer a global variable that is accessible to every VC. The app starts up in VC1, then I transitioned to VC2. There, I inserted this code: if let t = timer {t.invalidate()} and if timer.valid {timer.invalidate()}. Now that made not difference, the timer's selector method keeps printing stuff...
you should keep a reference to the timer in the viewcontroller that is "using" it...
class ViewController: UIViewController {
var timer: NSTimer?
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: Selector("timerFired"), userInfo: nil, repeats: true)
}
func timerFired() {
// do whatever you want
}
override func viewWillDisappear(animated: Bool) {
if timer != nil {
timer?.invalidate()
timer = nil
}
super.viewWillDisappear(animated)
}
}
Try this
import UIKit
class ViewController: UIViewController {
let timeInterval: NSTimeInterval = 5 // seconds
// The run loop maintains a strong reference already.
weak var timer: NSTimer?
func startTimer() {
// 1. invalidate previous timer if necessary
timer?.invalidate()
// 2. setup a new timer
timer = NSTimer.scheduledTimerWithTimeInterval(
timeInterval,
target: self,
selector: "timerFired",
userInfo: nil,
repeats: true
)
}
func stopTimer() {
timer?.invalidate()
timer = nil
}
// Need to include #objc marker here
// Function must not be private.
#objc internal func timerFired() {
/*
Perform any UI Updates or whatever...
*/
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
startTimer()
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
stopTimer()
}
}

Pausing and Recreating timers with notifications issue Swift

So I've got two timers, one that increases the score and one that spawns enemies. I used a notification to invalidate the timers, and then I'm using another one to recreate the timers. When I quit and then open the app, there are two sets of enemies being spawned on top of each other. I think timerRecreate = true and also the regular timers in GameScene are also being called.
GameViewController.swift file:
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("pauseTimers:"), name:UIApplicationWillResignActiveNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("startTimers:"), name:UIApplicationDidBecomeActiveNotification, object: nil)
}
func pauseTimers(notification : NSNotification) {
println("Observer method called")
timer.invalidate()
scoretimer.invalidate()
}
func startTimers(notification : NSNotification) {
println("Observer method called")
timerRecreate = true
}
Code for timers in GameScene.swift
override func didMoveToView(view: SKView) {
//Spawn timer for enemy blocks
timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: Selector("spawnEnemies"), userInfo: nil, repeats: true)
//Timer for keeping score
scoretimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("scoreCounter"), userInfo: nil, repeats: true)
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
if timerRecreate == true {
//Spawn timer for enemy blocks
timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: Selector("spawnEnemies"), userInfo: nil, repeats: true)
//Timer for keeping score
scoretimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("scoreCounter"), userInfo: nil, repeats: true)
timerRecreate = false
}
}
I think the problem is when you initially open the app, be that after quitting out of it or opening it for the first time, timerRecreate is set to true as well as the regular spawning of blocks so two sets of blocks are spawned at the same time. How can I fix this?
Fixed it! I hope...
Anyway heres what I did. I created another boolean called timerz and set it to false when the DidBecomeActive notification was made. At the same time, timeRecreate is set to true. This guarantees that both timer sets arent running at the same time. In the update function inside the if statement on whether timRecreate was true, I set timeRecreate to false and timerz to true. So the timers are recreated and then it switches back to to old way of spawning them. I also put this old method of spawning them inside an if statement on whether timerz was true or false.

Resources