[SwiftUI]アプリ起動時、バックグラウンド時などの取得

目次

概要

アプリをバックグラウンドにしたときの処理などを実装する。
アプリ全体ではなく、画面単位で行いたかったためメモ。

ソースコード

import SwiftUI

@main
struct TestApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {
        WindowGroup {
            ApplicationNotificationView()
        }
    }
}
import SwiftUI

struct ApplicationNotificationView: View {
    var body: some View {
        ZStack {
            Text("アプリ起動などの通知")
        }
        .onReceive(NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)) { notification in
            print("--------didBecomeActiveNotification--------")
            print("アクティブになった。")
            print("--------didBecomeActiveNotification--------")
        }
        .onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { notification in
            print("--------willResignActiveNotification--------")
            print("非活性になるよ。")
            print("--------willResignActiveNotification--------")
        }
        .onReceive(NotificationCenter.default.publisher(for: UIApplication.didEnterBackgroundNotification)) { notification in
            print("--------didEnterBackgroundNotification--------")
            print("バックグランドになった。")
            print("--------didEnterBackgroundNotification--------")
        }
        .onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { notification in
            print("--------willEnterForegroundNotification--------")
            print("フォアグラウンドになるよ。")
            print("--------willEnterForegroundNotification--------")
        }
        .onReceive(NotificationCenter.default.publisher(for: UIApplication.willTerminateNotification)) { notification in
            print("--------willTerminateNotification--------")
            print("アプリ終了するよ。")
            print("--------willTerminateNotification--------")
        }
        .onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { _ in
            print("--------UIDevice.orientationDidChangeNotification--------")
            print("画面が回転したよ")
            print("--------UIDevice.orientationDidChangeNotification--------")
        }
    }
}

詳細

使い方としては、onReceiveで通知を受け取る。
そして、NotificationCenter.default.publisherでどんな動作が行われたか検知する。
種類はAppleの公式ドキュメントに記載されている。

通知の種類

通知の種類呼ばれるタイミング
didBecomeActiveNotificationアプリがアクティブ状態になったとき
アプリ起動時も呼ばれる
willResignActiveNotificationアプリが非活性になったとき
アプリ一覧を表示したときがこのタイミング
didEnterBackgroundNotificationアプリがバックグラウンドになったとき
willEnterForegroundNotificationアプリがバックグラウンドからフォアグラウンドになったとき
willTerminateNotificationアプリがタスクキルされたとき
UIDevice.orientationDidChangeNotification画面が回転したとき