How do I keep my SwiftUI previews from running in the background after I close them?

141 Views Asked by At

I am developing a game with Swift / Xcode / SwiftUI, and Xcode's preview window is great for iterating on changes quickly. But I noticed that when I close the preview canvas, my app is still running in Activity Monitor, taking up lots of CPU, even though Xcode's preview window is not showing--and I usually run killall MyAppName on the terminal to stop the process. You can also tell that it's still running because it still responds to game controller input and plays sound effects! (If I don't kill the app, all my subsequent builds are slower, since my laptop is still running my game in the background while building...)

As far as I can tell, my normal AppDelegate methods are not getting called in a preview context, so catching things like application(application:, didDiscardSceneSesssions:) doesn't work for this problem. I tried overriding application(application: didDiscardSceneSessions:), but it wasn't called.

Anyone have any ideas for how to "tell" that my app, when running as a preview, is "not showing" as a preview anymore? I'd like to have it automatically kill its own process, or I guess ideally gracefully quit.

0

There are 0 best solutions below