Search code examples
iosswiftuiapplication

Swift: Shut down app after countdown


I created a 4:00 minute countdown timer with an acoustic signal when it reaches 0:00. I used a function that prevents the phone from falling asleep while the timer is running. However, this is the last screen of my app. So once the acoustig final signal is over, I'd like the app to slowly shut down. I don't know where to place the code.

This is the code I used to prevent it from falling asleep:

override func viewDidLoad() {
    super.viewDidLoad()

    UIApplication.sharedApplication().idleTimerDisabled = true
}

So I thought I could use

UIApplication.sharedApplication().idleTimerDisabled = false

to reverse it. When I place it inside the stopTimer function, it shuts down immediately at 0:00.

func stopTimer() {
    if count == 0 {
        timer.invalidate()
        timerRunning = false
        playSound()
        timerLabel.text = "DONE"
    }
}

Maybe there's a way to lag the process so that it shuts down after 15 seconds. How do I do this?


Solution

  • As written in my comment and in the linked answer you could use dispatch_after:

    let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(15 * Double(NSEC_PER_SEC))) // the 15 indicates the seconds to wait
    dispatch_after(delayTime, dispatch_get_main_queue()) {
        UIApplication.sharedApplication().idleTimerDisabled = false
    }