TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Saving a state on sceneDidEnterBackground

Forums > SwiftUI

Hello,

I am currently working on a simple puzzle game and I have a challenge that I am not sure how to tackle. Right now, when user minimalizes my game and starts to do other tasks, after a while the game starts from scratch and doesn't keep their game state.

Preferably, I would like to use UserDefaults to store the state (it's an array of objects and a couple of bools). But, here are the things that I am not sure about:

  1. Should I save the state to UserDefaults every time it changes or only when the app is minimalized?
  2. I tried to use different methods to trigger a behavior (print something to console) on app minimalize and the only way that works for me is sceneDidEnterBackground() inside SceneDelegate. My build target is set up to iOS 13.0 so I think I should be using applicationDidEnterBackground() inside AppDelegate (I have both files). Is it a proper behavior?
  3. If saving/loading should happen inside SceneDelegate, where I should retrieve the state of the game? Inside sceneWillEnterForeground() or sceneDidBecomeActive() or maybe inside init() of the game?

Thank you for any advice, Piotr

2      

I found a solution that works best for me - https://www.hackingwithswift.com/books/ios-swiftui/how-to-be-notified-when-your-swiftui-app-moves-to-the-background

The way my code looks like is similar to this:

HomeView()
    .onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { _ in
        //saveData()

    }
    .onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
        //loadData()

    }

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.