I am working on meditation app. In this app i have some musical content and some silent meditation section using timer. Timer is working fine when it is in foreground but it is running for only 3 min in background(when device is locked or user press home button to exit from the app). I am using swift4. What i have tried :
var timer: Timer!
var timeCounter : Int!
var backgroundTaskIdentifier: UIBackgroundTaskIdentifier?
var backgroundTask = BackgroundTask()
#IBOutlet weak var timeLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: {
UIApplication.shared.endBackgroundTask(self.backgroundTaskIdentifier!)
})
backgroundTask.startBackgroundTask()
DispatchQueue.global(qos: .background).async {
let currentRunLoop = RunLoop.current
let timeInterval = 1.0
self.timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(self.updateTimer), userInfo: nil, repeats: true)
self.timer.tolerance = timeInterval * 0.1
currentRunLoop.add(self.timer, forMode: .commonModes)
currentRunLoop.run()
}
}
}
#objc func updateTimer () {
timeCounter = timeCounter - 1
let minutes = Int(timeCounter) / 60 % 60
let seconds = Int(timeCounter) % 60
print("timeCounter", timeCounter)
if (timeCounter == 0){
if self.timer != nil {
self.timer?.invalidate()
self.timer = nil
player.play()
}
}
timeLabel.fadeTransition(0.4)
timeLabel.text = String(format: "%02i:%02i",minutes,seconds)
}
Thanks in Advance.
In general you get limited time from the OS to run in background. You can check and react to the background time left using:
UIApplication.shared.backgroundTimeRemaining
If conditions are good (device is unlocked, battery full ...) you typically get about 160-180 seconds.
You find detailed information in Apples documentation.
As you want to play audio, you can use "Plays Audio" background mode to not get cut by the OS:
Depending how you play audio, configuring the AudioSession might also improve things.
Edit:
How I understand now from your comment, you want your app to do something every 4 minutes. The only possiblility I see is to use the BackgroundFetch feature. This does not guarantee a fixed interval though.
Related
I want to create a timer that should fire every hour. But from my research, an app gets suspended after 10 mins in the background. It also seems like the app gets suspended after the screen is locked.
I want to trigger this timer every 1 hour. I will be invalidating the timer when app goes in the background and restart it when the app foregrounds. So I have a few questions:
When the user backgrounds the app and comes back to it, will the timer fire immediately if it has been 1+ hour?
What happens if the user returns to the app after multiple (2+) hours, will the timer fire multiple times?
Are there any recommended ways to setup such longer running timers so they fire more consistently and not just once when they were setup?
You can do something like this without using background timer. It is only idea how you can achieve your requirement, add one or more hours condition as per your requirement.
var totalTime = Double()
override func viewDidLoad() {
super.viewDidLoad()
// MARK: - To Reset timer's sec if app is in background and foreground
NotificationCenter.default.addObserver(self, selector: #selector(self.background(_:)), name: UIApplication.didEnterBackgroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.foreground(_:)), name: UIApplication.willEnterForegroundNotification, object: nil)
}
#objc func background(_ notification: Notification) {
if self.totalTime > 0{
user_default.setValue(self.totalTime, forKey: "TotalSecInBackground")
user_default.setValue(Date().timeIntervalSince1970, forKey: "OldTimeStamp")
LogInfo("total seconds left in background: \(self.totalTime)")
}
}
#objc func foreground(_ notification: Notification) {
let timerValue: TimeInterval = user_default.value(forKey: "TotalSecInBackground") as? TimeInterval ?? 0
let otpTimeStamp = user_default.value(forKey: "OldTimeStamp") as? TimeInterval ?? 0
let timeDiff = Date().timeIntervalSince1970 - otpTimeStamp
if timerValue > timeDiff{
LogInfo("total second & timeDiff:, \(Int(timerValue)),\(Int(timeDiff))")
let timeLeft = timerValue - timeDiff
self.totalTime = Int(timeLeft)
LogInfo("timeLeft: \(Int(timeLeft))") // <- This is what you need
}}
I am creating a timer on my app in iOS which counts down from 20 minutes to 0 seconds, one second at a time. So far the timer works but only counts down for 20 seconds, not minutes. It also doesn't stop when it gets to zero. How can this be resolved?
import UIKit
class SkippingViewController: UIViewController {
#IBOutlet weak var timeLabel: UILabel!
#IBOutlet weak var startWorkoutButton: UIButton!
#IBOutlet weak var pauseWorkoutButton: UIButton!
var timer = Timer()
var counter = 20.00
var isRunning = false
override func viewDidLoad() {
super.viewDidLoad()
timeLabel.text = "\(counter)"
startWorkoutButton.isEnabled = true
pauseWorkoutButton.isEnabled = false
}
#IBAction func startWorkoutButtonDidTouch(_ sender: Any) {
if !isRunning {
timer = Timer.scheduledTimer(timeInterval: -0.01, target: self, selector: #selector(SkippingViewController.updateTimer), userInfo: nil, repeats: true)
startWorkoutButton.isEnabled = false
pauseWorkoutButton.isEnabled = true
isRunning = true
}
}
#IBAction func pauseWorkoutButtonDidTouch(_ sender: Any) {
startWorkoutButton.isEnabled = true
pauseWorkoutButton.isEnabled = false
timer.invalidate()
isRunning = false
}
#objc func updateTimer() {
counter -= 0.01
timeLabel.text = String(format: "%.01f", counter)
}
There's a couple of issues that I see with your code that prevent it from working the way you want.
First of all, if the timeInterval passed in the scheduledTimer method is negative, it will always lead to a timer being created that fires every 0.1 milliseconds (source: documentation).
What you want is your updateTimer to be called every second, so just pass 1.0 to the scheduledTimer method, e.g.:
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(SkippingViewController.updateTimer), userInfo: nil, repeats: true)
Furthermore, you want to invalidate this timer when 20 minutes have passed since starting the timer. So when setting up the timer you could keep track of the current time, and when that time + 20 minutes is more than the current time when called in updateTimer, you can invalidate the timer. With other words, instead of counting down from 20 minutes, we are counting from 0 til 20 minutes have passed!
Example code (didn't try compiling it, but should work, let me know if it doesn't):
import UIKit
class SkippingViewController: UIViewController {
#IBOutlet weak var timeLabel: UILabel!
#IBOutlet weak var startWorkoutButton: UIButton!
#IBOutlet weak var pauseWorkoutButton: UIButton!
var timer = Timer()
var countDownFromMinutes = 20
var timerStartTime: Date?
override func viewDidLoad() {
super.viewDidLoad()
timeLabel.text = "\(countDownFromMinutes):00"
startWorkoutButton.isEnabled = true
pauseWorkoutButton.isEnabled = false
}
#IBAction func startWorkoutButtonDidTouch(_ sender: Any) {
if !timer.isValid {
// run every second
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(SkippingViewController.updateTimer), userInfo: nil, repeats: true)
timerStartTime = nil
startWorkoutButton.isEnabled = false
pauseWorkoutButton.isEnabled = true
}
}
#IBAction func pauseWorkoutButtonDidTouch(_ sender: Any) {
startWorkoutButton.isEnabled = true
pauseWorkoutButton.isEnabled = false
timer.invalidate()
}
#objc func updateTimer() {
guard let startTime = timerStartTime else {
// first firing
timeLabel.text = "\(countDownFromMinutes):00"
timerStartTime = Date()
return
}
let now = Date()
let calendar = Calendar.current
// this ordinarily never returns nil, return gracefully if so
guard let endTime = calendar.date(byAdding: .minute, value: countDownFromMinutes, to: startTime) else {
return
}
let differenceMinuteSeconds = Calendar.current.dateComponents([.minute, .second], from: now, to: endTime)
// 20 minutes have passed since start
if now >= endTime {
timeLabel.text = "00:00"
timer.invalidate()
return
}
timeLabel.text = String(format: "%02d:%02d", differenceMinuteSeconds.minute ?? 0, differenceMinuteSeconds.seconds ?? 0)
}
}
Note that I also replaced the isRunning var you added with using timer.isValid as I believe it would achieve the same without introducing another variable.
Only thing that is probably left is regarding the text of label you are displaying. I am not sure what you actually want to display here. If you can add that in the comments I can suggest an approach for that.
You’ve set your timer’s interval to fire every 0.01 seconds, i.e. 100 times per second. And you’re adjusting the counter by 0.01 each time. So that means that it will decrement the counter at a rate of 1 per second. So a counter of 20 will expire in 20 seconds, not 20 minutes. If you want 20 minutes using your counter mechanism, you’d use 20 * 60.
A couple of other observations:
Timers are not guaranteed to fire at the requested interval. It’s safer to save the time to which you’re counting down (or the time you started) and calculate the time elapsed from that. Then you can update the label with a nice string representation of the time elapsed.
You’re firing your timer every hundredth of a second. But screens don’t generally update with that frequency. Besides, you’re just showing minutes and seconds, so updating more frequently than that offers no benefit.
If I were, though, showing milliseconds, and wanted an optimal timer frequency, I’d use a CADisplayLink rather than a timer. And, in the spirit of point 1, above, if you are using “start”/“stop” date to calculate how much time has elapsed, rather than a counter, you don’t have to worry about what this refresh rate is, since we’re no longer decrementing a counter.
Sorry if this is a newbie question, I am very new to iOS & Swift. I have a problem with the timer interval: I set 0.01 time interval but it doesn't correspond with the timer label, because 0.01 corresponds in one millisecond but it doesn't show it. So basically the timer is skewed.
timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(updateStopwatch) , userInfo: nil, repeats: true)
#IBAction func startStopButton(_ sender: Any) {
buttonTapped()
}
func updateStopwatch() {
milliseconds += 1
if milliseconds == 100 {
seconds += 1
milliseconds = 0
}
if seconds == 60 {
minutes += 1
seconds = 0
}
let millisecondsString = milliseconds > 9 ?"\(milliseconds)" : "0\(milliseconds)"
let secondsString = seconds > 9 ?"\(seconds)" : "0\(seconds)"
let minutesString = minutes > 9 ?"\(minutes)" : "0\(minutes)"
stopWatchString = "\(minutesString):\(secondsString).\(millisecondsString)"
labelTimer.text = stopWatchString
}
func buttonTapped() {
if isTimerRunning {
isTimerRunning = !isTimerRunning
timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(updateStopwatch) , userInfo: nil, repeats: true)
startStopButton.setTitle("Stop", for: .normal)
}else{
isTimerRunning = !isTimerRunning
timer.invalidate()
startStopButton.setTitle("Start", for: .normal)
}
}
Devices have maximum screen update rate (most are 60 fps), so there is no point in going faster than that. For maximum screen refresh rate, use a CADisplayLink rather than a Timer, which is coordinated perfectly for screen refreshes (not only in frequency, but also the timing within the screen refresh cycle).
Also don't try to keep track of the time elapsed by adding some value (because you are not guaranteed that it will be called with the desired frequency). Instead, before you start your timer/displaylink, save the start time and then when the timer/displaylink is called, display the elapsed time in the desired format.
For example:
var startTime: CFTimeInterval!
weak var displayLink: CADisplayLink?
func startDisplayLink() {
self.displayLink?.invalidate() // stop prior display link, if any
startTime = CACurrentMediaTime()
let displayLink = CADisplayLink(target: self, selector: #selector(handleDisplayLink(_:)))
displayLink.add(to: .current, forMode: .commonModes)
self.displayLink = displayLink
}
func handleDisplayLink(_ displayLink: CADisplayLink) {
let elapsed = CACurrentMediaTime() - startTime
let minutes = Int(elapsed / 60)
let seconds = elapsed - CFTimeInterval(minutes) * 60
let string = String(format: "%02d:%05.2f", minutes, seconds)
labelTimer.text = string
}
func stopDisplayLink() {
displayLink?.invalidate()
}
Note, CACurrentMediaTime() uses mach_time, like hotpaw2 correctly suggested, but does the conversion to seconds for you.
The time delay of a scheduledTimer is only approximate, and can differ from what is requested by many milliseconds, due to iOS overhead. A repeating Timer is even worse for timing, as any delay jitter errors will accumulate. So don't use a Timer for timing longer events.
A CADisplayLink is a more reliable timer, as it is synchronized to the 60 Hz display refresh (e.g. this is the maximum rate that any UILabel can be changed on devices other than the latest iPad Pros). There is no use trying to update a time display any faster (except possibly on the latest iPad Pros).
Also, do not use Date methods for timing, as they are not guaranteed to be monotonic when the device is connected to a network (as NTP can change the clock time right in the middle of your timing activity).
You should check any elapsed time measurement UI against one of the built-in timers such as mach_time. mach_absolute_time() is guaranteed to be monotonic, and not affected by NTP or other network activity.
i am trying to do an application which can make a timer run in background.
here's my code:
let taskManager = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(self.scheduleNotification), userInfo: nil, repeats: true)
RunLoop.main.add(taskManager, forMode: RunLoopMode.commonModes)
above code will perform a function that will invoke a local notification.
this works when the app is in foreground, how can i make it work in the background?
i tried to put several print lines and i saw that when i minimize (pressed the home button) the app, the timer stops, when i go back to the app, it resumes.
i wanted the timer to still run in the background. is there a way to do it?
here's what i want to happen:
run app -> wait 10 secs -> notification received -> wait 10 secs -> notification received -> and back to wait and received again
that happens when in foreground. but not in background. pls help.
you can go to Capabilities and turn on background mode and active Audio. AirPlay, and picture and picture.
It really works . you don't need to set DispatchQueue .
you can use of Timer.
Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (t) in
print("time")
}
Swift 4, Swift 5
I prefer to not run timer on background task, just compare a Date seconds between applicationDidEnterBackground and applicationWillEnterForeground.
func setup() {
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground(_:)), name: UIApplication.didEnterBackgroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground(_:)), name: UIApplication.willEnterForegroundNotification, object: nil)
}
#objc func applicationDidEnterBackground(_ notification: NotificationCenter) {
appDidEnterBackgroundDate = Date()
}
#objc func applicationWillEnterForeground(_ notification: NotificationCenter) {
guard let previousDate = appDidEnterBackgroundDate else { return }
let calendar = Calendar.current
let difference = calendar.dateComponents([.second], from: previousDate, to: Date())
let seconds = difference.second!
countTimer -= seconds
}
This works. It uses while loop inside async task, as suggested in another answer, but it is also enclosed within a background task
func executeAfterDelay(delay: TimeInterval, completion: #escaping(()->Void)){
backgroundTaskId = UIApplication.shared.beginBackgroundTask(
withName: "BackgroundSound",
expirationHandler: {[weak self] in
if let taskId = self?.backgroundTaskId{
UIApplication.shared.endBackgroundTask(taskId)
}
})
let startTime = Date()
DispatchQueue.global(qos: .background).async {
while Date().timeIntervalSince(startTime) < delay{
Thread.sleep(forTimeInterval: 0.01)
}
DispatchQueue.main.async {[weak self] in
completion()
if let taskId = self?.backgroundTaskId{
UIApplication.shared.endBackgroundTask(taskId)
}
}
}
}
A timer can run in the background only if both the following are true:
Your app for some other reason runs in the background. (Most apps don't; most apps are suspended when they go into the background.) And:
The timer was running already when the app went into the background.
Timer won't work in background. For background task you can check this link below...
https://www.raywenderlich.com/143128/background-modes-tutorial-getting-started
============== For Objective c ================
create Global uibackground task identifier.
UIBackgroundTaskIdentifier bgRideTimerTask;
now create your timer and add BGTaskIdentifier With it, Dont forget to remove old BGTaskIdentifier while creating new Timer Object.
[timerForRideTime invalidate];
timerForRideTime = nil;
bgRideTimerTask = UIBackgroundTaskInvalid;
UIApplication *sharedApp = [UIApplication sharedApplication];
bgRideTimerTask = [sharedApp beginBackgroundTaskWithExpirationHandler:^{
}];
timerForRideTime = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:#selector(timerTicked:)
userInfo:nil
repeats:YES];
[[NSRunLoop currentRunLoop]addTimer:timerForRideTime forMode: UITrackingRunLoopMode];
Here this will work for me even when app goes in background.ask me if you found new problems.
You can achieve this by getting the time-lapse between background and foreground state of the app, here is the code snippet.
import Foundation
import UIKit
class CustomTimer {
let timeInterval: TimeInterval
var backgroundTime : Date?
var background_forground_timelaps : Int?
init(timeInterval: TimeInterval) {
self.timeInterval = timeInterval
}
private lazy var timer: DispatchSourceTimer = {
let t = DispatchSource.makeTimerSource()
t.schedule(deadline: .now() + self.timeInterval, repeating: self.timeInterval)
t.setEventHandler(handler: { [weak self] in
self?.eventHandler?()
})
return t
}()
var eventHandler: (() -> Void)?
private enum State {
case suspended
case resumed
}
private var state: State = .suspended
deinit {
NotificationCenter.default.removeObserver(self, name: UIApplication.didEnterBackgroundNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIApplication.willEnterForegroundNotification, object: nil)
timer.setEventHandler {}
timer.cancel()
resume()
eventHandler = nil
}
func resume() {
NotificationCenter.default.addObserver(self, selector: #selector(didEnterBackgroundNotification), name: UIApplication.didEnterBackgroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForegroundNotification), name: UIApplication.willEnterForegroundNotification, object: nil)
if state == .resumed {
return
}
state = .resumed
timer.resume()
}
func suspend() {
if state == .suspended {
return
}
state = .suspended
timer.suspend()
}
#objc fileprivate func didEnterBackgroundNotification() {
self.background_forground_timelaps = nil
self.backgroundTime = Date()
}
#objc fileprivate func willEnterForegroundNotification() {
// refresh the label here
self.background_forground_timelaps = Date().interval(ofComponent: .second, fromDate: self.backgroundTime ?? Date())
self.backgroundTime = nil
}
}
Use this class like;
self.timer = CustomTimer(timeInterval: 1)
self.timer?.eventHandler = {
DispatchQueue.main.sync {
var break_seconds = self.data.total_break_sec ?? 0
break_seconds += 1
if self.timer?.background_forground_timelaps != nil && self.timer?.backgroundTime == nil{
break_seconds += (self.timer?.background_forground_timelaps)!
self.timer?.background_forground_timelaps = nil
}
self.data.total_break_sec = String(break_seconds)
self.lblBreakTime.text = PRNHelper.shared.getPlainTimeString(time: TimeInterval(break_seconds))
}
}
self.timer?.resume()
This way I am able to get the timer right when resumed the app from background.
If 1 or 2 seconds threshold is acceptable this hack could be helpful.
UIApplication.didEnterBackgroundNotification
UIApplication.willEnterForegroundNotification
Stop Timer and Backup Date() on didEnterBackground.
Add Date() to the Backup date on willEnterForegraound to achieve total time.
Start Timer and Add total date to the Timer.
Notice: If user changed the date time of system it will be broken!
You dont really need to keep up with a NSTImer object. Every location update comes with its own timestamp.
Therefore you can just keep up with the last time vs current time and every so often do a task once that threshold has been reached:
if let location = locations.last {
let time = location.timestamp
guard let beginningTime = startTime else {
startTime = time // Saving time of first location time, so we could use it to compare later with subsequent location times.
return //nothing to update
}
let elapsed = time.timeIntervalSince(beginningTime) // Calculating time interval between first and second (previously saved) location timestamps.
if elapsed >= 5.0 { //If time interval is more than 5 seconds
//do something here, make an API call, whatever.
startTime = time
}
}
As others pointed out, Timer cannot make a method run in Background. What you can do instead is use while loop inside async task
DispatchQueue.global(qos: .background).async {
while (shouldCallMethod) {
self.callMethod()
sleep(1)
}
}
I am trying to create a timer to countdown x minutes and y seconds.
I am computing the number of seconds and creating the InterfaceTimer like this:
timer.setDate(NSDate(timeIntervalSinceNow:Double(secondsValue+1)))
timer.stop()
after that I keep stoping it and starting it again and again, but the values are suddenly decreasing as "time(now) doesn't stop".
Eg: if the timer shows :55, I start it for 3sec and stop it, it shows :52, I wait 10seconds and then start it again, it starts from :42.
I can not save the value currently in the WKInterfaceTimer, so that I could start again from the same point. Everything I tried doesn't work. Did anyone work with the timer and it stayed at the same value after stopping it?
Yes the watchkit timer is a bit...awkward...and definitely not very intuitive. But that's just my opinion
You'll have to keep setting the date/timer each time the user chooses to resume the timer.
Remember, you'll also need an internal NSTimer to keep track of things since the current WatchKit timer is simply for display without having any real logic attached to it.
So maybe something like this...It's not elegant. But it works
#IBOutlet weak var WKTimer: WKInterfaceTimer! //watchkit timer that the user will see
var myTimer : NSTimer? //internal timer to keep track
var isPaused = false //flag to determine if it is paused or not
var elapsedTime : NSTimeInterval = 0.0 //time that has passed between pause/resume
var startTime = NSDate()
var duration : NSTimeInterval = 45.0 //arbitrary number. 45 seconds
override func willActivate(){
super.willActivate()
myTimer = NSTimer.scheduledTimerWithTimeInterval(duration, target: self, selector: Selector("timerDone"), userInfo: nil, repeats: false)
WKTimer.setDate(NSDate(timeIntervalSinceNow: duration ))
WKTimer.start()
}
#IBAction func pauseResumePressed() {
//timer is paused. so unpause it and resume countdown
if isPaused{
isPaused = false
myTimer = NSTimer.scheduledTimerWithTimeInterval(duration - elapsedTime, target: self, selector: Selector("timerDone"), userInfo: nil, repeats: false)
WKTimer.setDate(NSDate(timeIntervalSinceNow: duration - elapsedTime))
WKTimer.start()
startTime = NSDate()
pauseResumeButton.setTitle("Pause")
}
//pause the timer
else{
isPaused = true
//get how much time has passed before they paused it
let paused = NSDate()
elapsedTime += paused.timeIntervalSinceDate(startTime)
//stop watchkit timer on the screen
WKTimer.stop()
//stop the ticking of the internal timer
myTimer!.invalidate()
//do whatever UI changes you need to
pauseResumeButton.setTitle("Resume")
}
}
func timerDone(){
//timer done counting down
}