NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

How to be notified when your SwiftUI app moves to the background

Paul Hudson    @twostraws   

SwiftUI can detect when your app moves to the background (i.e., when the user returns to the home screen), when it comes back to the foreground, when the user takes a screenshot, and much more. This is all powered by Notification Center, which is the name for Apple’s internal message system – API that lets the system notify us when events happen, but also lets us post messages between different parts of our code.

Notification Center is another thing that comes from Apple’s Foundation framework, and in SwiftUI we can monitor its events using Combine, so really this is three of Apple’s frameworks working together to give us some great functionality.

For example, Notification Center posts a message called UIApplication.willResignActiveNotification when your app starts to move to the background, which gives us the chance to pause any work that isn’t critical, save our data, and more. To use it, we need to ask Notification Center to create a publisher for that notification, then attach whatever work we want. We’ll be given the actual message that occurred as a parameter to our closure, but most of the time you can ignore this.

So, try this to have a message printed out when the user leaves your app:

Text("Hello, World!")
    .onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { _ in
        print("Moving to the background!")
    }

There are lots of these notifications that we can listen for, and they all work in exactly the same way. For example, the opposite of willResignActiveNotification is willEnterForegroundNotification, which is called when the user has re-activated your app and is your chance to continue any important work:

Text("Hello, World!")
    .onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
        print("Moving back to the foreground!")
    }

You can even detect when the user took a screenshot, using userDidTakeScreenshotNotification:

Text("Hello, World!")
    .onReceive(NotificationCenter.default.publisher(for: UIApplication.userDidTakeScreenshotNotification)) { _ in
        print("User took a screenshot!")
    }

There are so many of these that I can’t realistically list them all here, so instead here are two more to try out:

  • UIApplication.significantTimeChangeNotification is called when the user changes their clock or when daylight savings time changes.
  • UIResponder.keyboardDidShowNotification is called when the keyboard is shown.

Each of these notifications works in exactly the same way: use onReceive() to catch notifications from the publisher, then take whatever action you want.

Hacking with Swift is sponsored by NSSpain

SPONSORED Announcing NSSpain 2020: Remote Edition! An online, continuous conference for iOS developers. We’ll start on Thursday and finish on Friday, with talks, activities, and lots of fun for 36 hours, non-stop. Sound good? Join us!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.4/5

Link copied to your pasteboard.