In my app I am having two view controller viewcontroller1
and viewcontroller2
. In view controller1
I am having one function called UpdateView()
I need to call this function for every 60 seconds
and I did it using DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 60)
. My problem is I want to run this function only when viewcontroller1
is in foreground, when user moved to viewcontroller2
I don't want to run this function any more. How to solve this?
Asked
Active
Viewed 323 times
0

rmaddy
- 314,917
- 42
- 532
- 579

Kavin Kumar Arumugam
- 1,792
- 3
- 28
- 47
2 Answers
1
You should stop the timer in viewDidDisappear and start your timer logic in viewDidAppear in the ViewController1.

Y_Y
- 331
- 1
- 6
1
You can do this easily with a Timer
. Inside viewWillAppear
method start the timer and inside the viewWillDisappear
stop or pause the timer.
var myTimer:Timer!
var myTimeInterval:TimeInterval = 60
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
myTimer = Timer.init(fire: Date(), interval: myTimeInterval, repeats: true, block: { (aTimer) in
//call the functio you want
UpdateView()
})
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
myTimer.invalidate()
}

Ravi
- 2,441
- 1
- 11
- 30