My ViewController.swift
func startTimer() {
timer = NSTimer().scheduleTimerWithTimerInvterval(1.0,target: self,selctor: Selector("couting"),userinfo: nil, repeats: true)
}
func pauseTimer() {
timer.invalidate()
println("pausing timer")
}
and this is appDelegate.swift
func applicateWillResignActive(application: UIApplication) {
viewController().pauseTimer()
println("closing app")
}
It is printing pausing timer and closing app but when I open again I see it never paused. How do I do it correctly?
Background timers are a very usefool tool in one’s developer toolbox. Most of the time when we want to schedule a repeating unit of work we consult NSTimer . Problem is, NSTimer requires an active… Sign in About Android iOS Web Backend Over Website A Background Repeating Timer in Swift Daniel Galasko Follow Aug 27, 2017·3min read
Timer is Swift is part of the Foundations framework so in order to use it in on your app you must import Foundations first. You are now ready to to timers in your app! The basic use for a timer is called the scheduledTimer where you need to set the timeInterval, selector, and repeats.
A timer can run in the background only if both the following are true: 1 Your app for some other reason runs in the background. (Most apps don't; most apps are suspended when they go into the... 2 The timer was running already when the app went into the background. More ...
So here’s what happens: The system resumes (or relaunches) your app in the background because the user enters your region. You schedule a timer for 3 minutes and start a background task to prevent the app from being suspended. After 30 seconds the background task expires.
Updated Answer for Swift 5:
NotificationCenter.default.addObserver
(self,
selector: #selector(myObserverMethod),
name:UIApplication.didEnterBackgroundNotification, object: nil)
@objc func myObserverMethod() {
print("Write Your Code Here")
}
You have to set an observer listening to when the application did enter background. Add the below line in your ViewController's viewDidLoad() method.
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("myObserverMethod:"), name:UIApplicationDidEnterBackgroundNotification, object: nil)
Add the below function to receive the notification.
func myObserverMethod(notification : NSNotification) {
println("Observer method called")
//You may call your action method here, when the application did enter background.
//ie., self.pauseTimer() in your case.
}
Happy Coding !!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With