keelo
keelo

Reputation: 261

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

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.

Upvotes: 5

Views: 714

Answers (1)

onexluv
onexluv

Reputation: 67

Hopefully Xcode will give us a Stop button for Previews soon, but in the meantime try these simple work-arounds:

1. Comment out your #Preview Declaration at the bottom of your view.

2. While your MainView's Preview is running, open up any other SwiftUI View with a simple Preview. Allow the new Preview to run, and then hide the Canvas (shortcut: Option+Command+Enter). Go back to your MainView and your preview should not be running in the background anymore.

(I tested this out on my MainView which consisted of a Published Timer and various print statements. Simply moving to another view stops my log from updating, and hiding the Canvas before re-entering my MainView keeps any further print statements from appearing in the log.)

Hope this helps, and lmk if anyone has a better way!

Upvotes: 2

Related Questions