Golden Mamba
Golden Mamba

Reputation: 1

how do I pause my app when the user exits, and resume it when they reenter the app?

I want my app to have the ability to run my pause function when the user clicks home. When I exit the app, it pauses, but then runs the view did load function when I enter the app again. Does anyone know how to have the view did load function only run the first time the view loads before it is termitated?

Here is my pause function:

func pauseGame322() {
    ThreeTime = 3
    CountdownUntillGameLabel.text = String(ThreeTime)
    if PlayButton.isHidden == true &&
        ContinueButton.isHidden == true{
        timer.invalidate()
        timer10.invalidate()
        TotalSecondsForPause.isHidden = false
        PauseView.isHidden = false
        UnpauseButton.isHidden = false
        TotalSecondsForPause.text = String(time)
    }
} 

Upvotes: 0

Views: 296

Answers (2)

Pallav Trivedi
Pallav Trivedi

Reputation: 326

You cannot limit the call of viewDidLoad. Every time the ViewController will be initialised, viewDidLoad will be called. To handle such scenario, what you can do is, put your code in a separate method, and call that method from viewDidLoad after performing the check for first time. To know that this is the first time or not, you can simply put a flag variable in UserDefaults.

Further, when you say 'User Exists', it may have different meanings. Did you mean that user kills the app, or you mean that user puts the app in background? For the first case, you should put the check for first time in applicationDidFinishLaunching method, while for the second case (i.e. background), call the pause function from applicationWillEnterBackground, and play from applicationDidEnterForeground.

Try using the application's life cycle methods in more efficient way.

Upvotes: 0

Code Different
Code Different

Reputation: 93181

Call your pause function from applicationWillResignActive(_:) in the App Delegate (emphasis mine):

You should use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. An app in the inactive state should do minimal work while it waits to transition to either the active or background state.

If you need access to the current view controller, follow this question. But updating the UI here is pointless. Your app is about to enter the background, the users won't see any UI changes. You display the pause menu when the user comes back, in applicationWillBecomeActive(_:).

Upvotes: 1

Related Questions