NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

SOLVED: how do I tell when my app goes into the background or comes into the foreground?

Forums > SwiftUI

I have a SwiftUI clock app that I'm writing from scratch with silly graphic numbers to make me giggle. I'm having an issue tho, when I launch the clock, if it has run before it shows what time it was when it passed into the background.

I have a Bool that if I can figure out how to set it to true when the app goes into or comes out of the background, all will be right with the world.

So my question is how do I tell when an app is doing that? going into the background or coming out of the background. either one would work for me, I just have one Bool that I need to set.

I've tried .onAppear and .onDisappear but they don't seem to work for me (maybe because my app only has 1 view?)

a screen shot of the happy digits

1      

If you stick this on your view, that'll do the trick:

        .onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { _ in
            // app is going to the background, so do something
        }
        .onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
            // app is coming to the foreground, so do something else
        }

1      

Thanks! That's exactly what I was looking for! it works like a charm!

1      

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

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.