SwiftUI/Protocol/Scene

アプリのユーザーインターフェースの一部で、システムによって管理されるライフサイクルのこと。

Scene
Typeprotocol
iOS14.0+
iPadOS14.0+
macOS11.0+
MacCatalyst14.0+
tvOS14.0+
watchOS7.0+
Websitedeveloper.apple.com/documentation/swiftui/scene/

環境変数scenePhaseを使うと onChange のときに状態に応じた処理分岐がかけられる。

enum型で、下記値をとる

.active
フォアグラウンドでインタラクティブな状態
.inactive
フォアグラウンドであるが作業がポーズ状態
.background
UIが現在表示されていない状態
struct MyScene: Scene {
    @Environment(\.scenePhase) private var scenePhase
    @StateObject private var cache = DataCache()

    var body: some Scene {
        WindowGroup {
            MyRootView()
        }
        .onChange(of: scenePhase) { newScenePhase in
            if newScenePhase == .background {
                cache.empty()
            }
        }
    }
}

External Link

【SwiftUI】Sceneプロトコルを読む