How to check app going to background in SwiftUI

Issue #746

From iOS 13, the default is to support multiple scene, so the the old UIApplicationDelegate lifecycle does not work. Double check your Info.plist for UIApplicationSceneManifest key

1
2
3
4
5
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<true/>
</dict>

One way to be notified about application life cycle is to use UIApplicationDelegateAdaptor and via NotificationCenter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import SwiftUI
import UIKit
import FontAwesomeSwiftUI

final class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
FontAwesome.register()
PreferenceManager.shared.load()
return true
}
}

@main
struct MyAwesomeApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self)
var appDelegate

var body: some Scene {
WindowGroup {
MainView(store: Store.shared)
.onReceive(
NotificationCenter.default.publisher(
for: UIApplication.didEnterBackgroundNotification)) { _ in
PreferenceManager.shared.save()
}
}
}
}

Comments