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


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


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


Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.