UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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

3      

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
        }

3      

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

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.