App running in background or when the screen is locked

Hi,

My app start to count the seconds when oppened. Follow the code:


import UIKit


class ViewController: UIViewController {


@IBOutlet weak var label1: UILabel! //Display showing the seconds

var i = 0 //Counter

override func viewDidLoad() {

super.viewDidLoad()

// After loading the view.

Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(Estouro), userInfo: nil, repeats: true)

}


@objc func Estouro(){


i = i + 1

label1.text = String(i) //Display seconds

}

}


What can I do to keep counting the secounds in background or after lock the screen?


Thank you,

Answered by DTS Engineer in 424189022

This is expected behaviour. Shortly after your app moves to the background the system suspends it. At that point all code running inside your app stops running, including any code run by timers.

How you deal with this depends on your specific requirements. The code snippet you posted is obviously a simplified example. What are you doing in your real app?

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
Accepted Answer

This is expected behaviour. Shortly after your app moves to the background the system suspends it. At that point all code running inside your app stops running, including any code run by timers.

How you deal with this depends on your specific requirements. The code snippet you posted is obviously a simplified example. What are you doing in your real app?

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Save the time when your app resigns active, and then when your app become active again use that time to calculate the new time

Thanks a lot for your both prompt answers.
@Eskimo, you are right, it is a simplified example. I'm working in a app able to send me alerts even in lockscreen after a preset period of time. Have you seen those Tabata workout app? It's quite similar.
@dqhieu, yes it could be a solution, but as I said I also need to receive an alert while the screen is locked... Any other suggestion?

I'm working in a app able to send me alerts even in lockscreen after a preset period of time.

Most folks use a local notification for this. Specifically, the UserNotifications framework supports UNTimeIntervalNotificationTrigger, which will trigger the notification after a specific time interval.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@apple.com"
App running in background or when the screen is locked
 
 
Q