0

I am working on a meditation app. In this app i am giving an option to the user to select the time up to 24hrs and do meditation. Timer is working fine for 3 min on lock screen but after 3 min it stopped.

Code is here :-

     var backgroundTaskIdentifier: UIBackgroundTaskIdentifier?

     var timer : Timer?
     var counter : Int!

    override func viewDidLoad() {
    super.viewDidLoad()
     backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: {
        UIApplication.shared.endBackgroundTask(self.backgroundTaskIdentifier!)
    })
     timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(MainPlayerMindCultivationController.updateTimer), userInfo: nil, repeats: true)

    }

 func updateTimer () {
    counter = counter - 1
    let hours = Int(counter) / 3600
    let minutes = Int(counter) / 60 % 60
    let seconds = Int(counter) % 60

    timerLabel.fadeTransition(0.4)
    timerLabel.text = String(format: "%02i:%02i:%02i",hours,minutes,seconds)

    print("mincounter\(counter)")

    }

Thanks in Advance.

Dixit Akabari
  • 2,419
  • 13
  • 26
Chetan Lodhi
  • 353
  • 1
  • 3
  • 21
  • 2
    For better idea read https://stackoverflow.com/questions/34862160/make-timer-run-on-background-ios-for-more-than-3-minutes – iPatel Oct 02 '17 at 06:29

1 Answers1

2

Timer is working fine for 3 min on lock screen but after 3 min it stopped.

That's just the way iOS works. You're supposed to invalidate your own timers when your app is interrupted and then restart them when your app starts running again. If you don't stop them yourself, though, your running timers will be invalidated by the OS when the app is suspended.

In this app i am giving an option to the user to select the time up to 24hrs and do meditation.

Local notifications would be a much better tool for this kind of thing. You can schedule a notification to happen at some point in the future, and the OS will take care of delivering the notification to the user. When the notification is delivered, the user will see your message and have the option to switch to your app even if the app isn't currently running at all.

Caleb
  • 124,013
  • 19
  • 183
  • 272